简体   繁体   中英

Do a jQuery/ajax POST on form submit

I have an html form like this:

<form action="myServer.com/test.php" method="post">
...
</form>

When the form is submitted, the user should be redirected to myServer.com/test.php and ofc send the post data to the script. BUT at the same time (or before), I want to post the same POST data to another script "myServer.com/test2.php".

$.post("myServer.com/test2.php", variableWithTheFormPOSTData);

I tried to attach an EventListener to the form submit, but that doesn't seem to work, maybe the jquery post cant be submitted fast enough before the redirection?

I hope you can help me. :(

每当在onsubmit中使用方法时,请确保其返回true,否则它将不会提交。

use a button as your submit button sothat the form doesnt get posted at the same time you click on it. And trigger the ajax function to post the data indirectly to the second page.

<form name="myform" action="myServer.com/test.php" method="post">
    ...
    <button onclick="doIndirectPost();"></button>
</form>

and in the success callback of ajax posting function trigger your form post

function doIndirectPost() {
    //initialize variableWithTheFormPOSTData here
    $.post("myServer.com/test2.php", variableWithTheFormPOSTData,function(success,error)    {
         //ajax post is completed now we trigger the form post to test.php
         document.myform.submit();

    });  
}

You can do it using ajax itself, which will avoid reloading the page

<form id="form1">
 .....
<input type="text" name="email"/> <!--Example input text box-->
<input type="button" id="submit"/> 
</form>

and the jquery code

$("#submit").click(function()
{
$.post("myServer.com/test2.php", $("#form1").serialize());//$("#form1).serialize() will get the data in the form automatically
$.post("myServer.com/test.php", $("#form1").serialize());

});

.serialize() will automatically serialize the data from the form that is to be posted

in your server side page use this

<?php
parse_str($_POST['serialize'], $data);
$name  = $data["email"] 


// do your code
?>

Hope this helps,Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM