SanketR SanketR - 4 days ago 6
jQuery Question

jQuery - Execute 2 functions synchronously

I have created a submit function for each form created on my application. It's similar to the one written below.

$('form').submit(function(){
//Some variable declaration
$.ajax({
type:'post',
url:'someurl',
data:formdata
success:function(){
console.log('form submitted');
}
});
});


No doubt this works fine. Now for one of the forms I want to update a certain element after the response is received, similar to this.

$('#customform').submit();
console.log('custom form submitted');


So in this case I want the message "custom form submitted" to be printed only after 'form submitted' message is printed to the console (Synchronous loading).
Anyone to help?

Answer

Just include the code into the success function:

success:function(){
  console.log('form submitted');
  console.log('custom form submitted');
}

You can also add complete function, so the code will run no matter if error or success:

success:function(){
  console.log('form submitted');
},
complete: function() {
  console.log('custom form submitted');
}

as @Tomalak mentioned in the comment, the modern way to do it:

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
.done(function() {
  alert( "second success" );
})
.fail(function() {
  alert( "error" );
})
.always(function() {
  alert( "finished" );
});

can read more here: jQuery.post( ) .done( ) and success:

Comments