I found, on this site a way to submit a POST
form without leaving the page. In that script, they put instructions on how to have a function take place after the form's been submitted. Here's what the script looked like:
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
},'json');
return false;
});
});
They said, between function(response){
and },'json');
you can specify other JavaScript to take place like alerts etc. after the form's been submitted. I tried
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
$('form').hide();
},'json');
return false;
});
});
Unfortunately, that does not work, can anybody tell me why? I've set up a jsFiddle. Please help. Thanks.
Problems:
form
, not$form
. Then use it in jQuery as$(form)
.$(this).attr('action')
is the$.post()
callback, not the form. Solution:$(form)
instead of$(this)
.Solution:
Your fiddle worked fine when the form is changed to
And the documentation at http://api.jquery.com/jQuery.post/ shows that this is a valid syntax and http://www.johnnycode.com/blog/2010/04/08/jquery-form-serialize-doesnt-post-submit-and-button-values-duh/ is also a running sample. If it's not working at all for you then, as silly as this is, do you have a reference to jQuery in your page?
Using $.post, the "function(response)" is only called AFTER a successful result, so you have been misinformed about doing work within this function while the server is processing the request.
To continue processing after sending the request to the server, place the $('form').hide() after the $.post call: