mellis481
mellis481

Reputation: 4158

jQuery ajax call race condition?

I have the following javascript function:

function deploy() {
    $.ajax({
        url: '/Theme/Deploy',
        type: 'POST'
    });
    location.reload();
}

This function is called when a button is clicked. I want to kick off the server call then immediately refresh the page. When I use the code above, it never makes the server call, it only refreshes the page. When I remove the location.reload() call, it makes the call successfully.

Is there a race condition or something happening where it reloads the page before the ajax call even though it's below it in code?

Upvotes: 0

Views: 382

Answers (2)

Vishwanath
Vishwanath

Reputation: 6004

Try calling the server as a script tag. I am not sure if this will work for sure, but in my tests it seemed to work making parallel requests.

function deploy(){
    var head = document.getElementsByTagName('head')[0];
    var sc = document.createElement('script');
    sc.setAttribute('src', '/Theme/Deploy');
    head.appendChild(sc);
    location.reload();
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The request is asynchronous. This means that the reload() is called before the request has completed.

To achieve what you require you should place the location.reload() inside the success handler of the AJAX call so it runs after the request completes:

function deploy() {
    $.ajax({
        url: '/Theme/Deploy',
        type: 'POST',
        success: function() {
            location.reload();
        }
    });
}

Upvotes: 3

Related Questions