linuxit

The linux way to do things

Wait until an jquery ajax request is completed before continuing

Sometimes, you need an ajax request to be completed to allow an application to continue as the rest of the process depends on it.  An example of this could be for instance when you are updating via ajax some database entries upon an user’s action.  Before allowing the web application to continue, you want to be sure that the row has been properly updated.

The typical way to achieve this is to add a delay using setTimeout or some obscure function (see http://stackoverflow.com/questions/1183872/put-a-delay-in-javascript) but of course, this method has a major drawback: you can never be absolutely sure that the delay will be long enough to let the operation finish.

A better way would be to simply specify that we want our ajax request to be sync instead of async (the default) by using {async: false} in our request :

$.ajax({
   type: "POST",
   async: false,
   url: "/ajax/newMemberGroup.php",
   data:  'name=' + $("#newMemberGroupInput").val() +'&selectOption=' + $("#memberGroup").html()
   }).done(function( msg ) {
   $("#memberGroup").html(msg);
});

That way, the rest of the code will only be executed once the ajax request is completed.  The only drawback of this method is that if your ajax request takes a long time, the browser can be locked for a long time (since we are waiting for our ajax request to be finished before continuing) but for a majority of cases where all you need is a quick  but crucial, operation, this method will do it!

Be Sociable, Share!

Categorised as: Web developemnt



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>