how to wait for an ajax call to return

I'm trying to use JQuery although i'm struggling to successfully wait for a ajax call to succeed before executing further code. Is there a way to wait for an ajax to call? I've seen examples but it seems just to wait blindly for x amount of seconds?

Thanks, James



Yes, you can do request synchronously:

var bodyContent = $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: {id : this.getAttribute('id')},
      dataType: "html",
      success: function(msg){


However, synchronous requests are a step backwards, as the JS engine (and, in some browsers, the user interface) will block until the request completes. Douglas Crockford once wrote about synchronous requests:

Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Have a look at jQuery deferreds. You can't halt this, but you can call other code after an AJAX call returns.

// No way to stop.

But with deferds you can:

$.ajax(...).success(function() {

See this article.


jQuery's ajax methods have a success handler.

You should put your code that you want to fire on success in a method attached to this handler.

Consider the example given on the jQuery website:

  url: "test.html",
  context: document.body,
  success: function(){

You can see here that there's a success handler with a method attached. This method will execute when the ajax method returns succesfully.

As has been pointed out in other answers and the comment below, you can now use deferreds instead of this simple success handeler. This allows you to attach multiple actions to each given event.


You have to insert your code in the 'success' function:

  1. Use async: false
  2. or use a callback function

You can use success or complete callbacks. Success fires if the server returns a 200. Complete will fire when the request is finished, regardless of the response status.

    url: "/path/to/action",
    success: function() {
        alert("do something if it's successful");
    complete: function(request, status) {
        alert("do something when it's finished, regardless of success.");

or you can do a synchronous call:

    url: "/path/to/action",
    async: false


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.