Submit two forms with one button

后端 未结 7 1609
面向向阳花
面向向阳花 2020-11-22 04:20

I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have

7条回答
  •  无人共我
    2020-11-22 04:50

    A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:

    var f = document.forms.updateDB;
    var postData = [];
    for (var i = 0; i < f.elements.length; i++) {
        postData.push(f.elements[i].name + "=" + f.elements[i].value);
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "mypage.php", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(postData.join("&"));
    
    document.forms.payPal.submit();
    

提交回复
热议问题