how to make a jquery "$.post" request synchronous
From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
Here's what your code would look like if changed as suggested:
beforecreate: function(node,targetNode,type,to) {
jQuery.ajax({
url: url,
success: function(result) {
if(result.isOk == false)
alert(result.message);
},
async: false
});
}
this is because $.ajax is the only request type that you can set the asynchronousity for
jQuery < 1.8
May I suggest that you use $.ajax()
instead of $.post()
as it's much more customizable.
If you are calling $.post()
, e.g., like this:
$.post( url, data, success, dataType );
You could turn it into its $.ajax()
equivalent:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});
Please note the async:false
at the end of the $.ajax()
parameter object.
Here you have a full detail of the $.ajax()
parameters: jQuery.ajax() – jQuery API Documentation.
jQuery >=1.8 "async:false" deprecation notice
jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:
- use a plugin e.g. BlockUI;
- manually add an overlay before calling
$.ajax()
, and then remove it when the AJAX.done()
callback is called.
Please have a look at this answer for an example.
If you want an synchronous request set the async
property to false
for the request. Check out the jQuery AJAX Doc