Is it possible to intercept a form's POST string and send it via AJAX instead? I could use $('form').submit() to intercept the POST event, but I don't see where I can get the POST string from. I could reproduce the string from the form's inputs, but this seems dubious.
A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.
You'll need to stop it BEFORE the success handler. Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late). But yes, put return false at the end of your function.
// capture submit
$('form').submit(function() {
var $theForm = $(this);
// send xhr request
$.ajax({
type: $theForm.attr('method'),
url: $theForm.attr('action'),
data: $theForm.serialize(),
success: function(data) {
console.log('Yay! Form sent.');
}
});
// prevent submitting again
return false;
});
Note that as Phil stated in his comment that .serialize()
doesn't include the submit button. If you also need to value of the submit buton you would have to add it manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With