How do I make jQuery wait for an Ajax call to finish before it returns?

Viewed 454423

I have a server side function that requires login. If the user is logged in the function will return 1 on success. If not, the function will return the login-page.

I want to call the function using Ajax and jQuery. What I do is submit the request with an ordinary link, with a click-function applied on it. If the user is not logged in or the function fails, I want the Ajax-call to return true, so that the href triggers.

However, when I use the following code, the function exits before the Ajax call is done.

How can I redirect the user gracefully to the loginpage?

$(".my_link").click(
    function(){
    $.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        cache: false,
        timeout: 30000,
        error: function(){
            return true;
        },
        success: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});
10 Answers

If you don't want the $.ajax() function to return immediately, set the async option to false:

$(".my_link").click(
    function(){
    $.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        async: false,
        cache: false,
        timeout: 30000,
        fail: function(){
            return true;
        },
        done: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});

But, I would note that this would be counter to the point of AJAX. Also, you should be handling the response in the fail and done functions. Those functions will only be called when the response is received from the server.

The underlying XMLHttpRequest object (used by jQuery to make the request) supports the asynchronous property. Set it to false. Like

async: false

In modern JS you can simply use async/await, like:

  async function upload() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: $(this).attr('href'),
            type: 'GET',
            timeout: 30000,
            success: (response) => {
                resolve(response);
            },
            error: (response) => {
                reject(response);
            }
        })
    })
}

Then call it in an async function like:

let response = await upload();

Since I don't see it mentioned here I thought I'd also point out that the jQuery when statement can be very useful for this purpose.

Their example looks like this:

$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  alert( jqXHR.status ); // Alerts 200
});

The "then" part won't execute until the "when" part finishes.

since async ajax is deprecated try using nested async functions with a Promise. There may be syntax errors.


async function fetch_my_data(_url, _dat) {

   async function promised_fetch(_url, _dat) {

      return new Promise((resolve, reject) => {
         $.ajax({
            url:  _url,
            data: _dat,
            type: 'POST',
            success: (response) => {
               resolve(JSON.parse(response));
            },
            error: (response) => {
               reject(response);
            }
         });
      });
   }

   var _data = await promised_fetch(_url, _dat);
   
   return _data;
}

var _my_data = fetch_my_data('server.php', 'get_my_data=1');

It should wait until get request completed. After that I'll return get request body from where function is called.

function foo() {
    var jqXHR = $.ajax({
        url: url,
        type: 'GET',
        async: false,
    });
    return JSON.parse(jqXHR.responseText);  
}

The original question was at today's date asked 12 years ago and was 'How do I make jQuery wait for an Ajax call to finish before it returns?' jQuery has come a long way since then.

There are a few solutions mentioned above and I couldn't get any of them to work with the latest version of jQuery: $.when().then.() doesn't seem to be synchronous unless its uses 'async: false' which is no longer supported, so doesn't work in newer versions of jQuery.

But promises are built into jQuery ajax calls so it shouldn't be that difficult to make ajax calls synchronous.

I use namespaced js functions so the example below is in that format. The example is for custom form validation that calls the server to validate that user input does not attempt to duplicate an existing item.

This code will probably not work in IE or Legacy Edge unless using Babel, but I tend to block those browsers as they are no longer supported by Microsoft.

///Namespace validate
check: async function(settings){
    let IsValid = false;
    let Message = ''
    let data = await validate.serverCheck('function', value);
    IsValid = data.OK;
    Message = data.Message;
}

serverCheck: async function (fn, value) {
    var request = {
        validateValue: $.sanitize(value)
    };

    let result;

    try {
            result = await $.ajax({
                dataType: "json",
                type: "post",
                url: "/api/validate/" + fn + "/",
                data: request
        });

        return result;
    } catch (x) {}
}

and there you have it

Related