pythonian29033 pythonian29033 - 11 months ago 61
HTML Question

how to make a jquery "$.post" request synchronous

I’ve been googling this and avoiding this error in my bug fix list for a long time now, but I’ve finally reached the end of the list, the last of which I have to make a function return true/false to state whether the validation has succeeded or not.

I'm using ajax to compare certain fields with those that are already in the db and by default the

method does it's operations asynchronously.

I’m setting a variable inside the call
and the calling method doesn't get a response because of this, so all my js/jquery fails on pageLoad... I would prefer if I could still keep using the

Answer Source

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:

  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,

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.

Edit: jQuery 1.8 "async:false" deprecation notice

For jQuery>=1.8 the solution shall differ a bit.

The idea now is, since now jQuery won't block the UI, to either use a plugin (e.g. BlockUI), or manually adding an overlay before calling $.ajax(), and then removing it from the AJAX .done() callback.

Please have a look at this answer for a possible implementation.