jQuery form post before submit
I have a page with a form on it that needs to post to an external URL. However, I also need this information to be sent to the current page (mypage.php). For security reasons, I cannot just post to mypage.php and use cURL to post via PHP to the external site - the form has to submit directly to the external site.
This code would be found on mypage.php and does not work (I assume that the submit of myform is not waiting for post):
$('#myform').submit(function() {
$.post('mypage.php', serializ开发者_运维百科ed_form,
function(data) {
...
}, 'html'
);
}
...
<form id="myform" action="http://example.org" method="post">
...
</form>
What is the best way to do something like this?
Thanks!
you can make the $.post() sync, which would block the javascript (and site) from continuing until its returned.
If you use $.ajax({type: 'post', async: false})
(plus your other params) that should do the trick.
You can read more info @ http://api.jquery.com/jQuery.ajax/
Will it work for you?
$('#myform').submit(function() {
$.post('mypage.php', serialized_form,
function(data) {
...
$.post('http://example.org', serialized_form, ....);
}, 'html'
);
return false;
}
<form id="myform" method="post">...</form>
If I understood your problem, then you need to your data to $url and still submit the form afterwards. Hope the following code works for you (not tested^^):
;(function($) {
var sent = false;
$('#myform').submit(function() {
if(sent) {
return true;
}
$.post('mypage.php', serialized_form,
function(data) {
sent = true;
$('#myform').submit();
},
'html'
);
return false;
});
})(jQuery);
精彩评论