AndrewL AndrewL - 1 month ago 15
jQuery Question

Ajax when request complete with no response

I have created an AJAX request, which after it is done it redirects the page. It ignores the response.

I am trying to get it to make sure it has finished sending the POST before it redirects. Everything I find online has how to get it to trigger something after it has a success or failure. I don't want to wait that long. Is there a way to get it to just wait till it has sent the POST then do something?

$.ajax({
data: "type=userLoginLog&username=" + username, //Post Username
url: environmentalVariables.support_api_address
});
loginWithRefreshToken(refresh_token);

Answer

No, there is no way to know exactly when it has sent. The only notification you get from Ajax is when the response or error is received or the request timed out. There is no "sent now" notification.

You could experiment and do the redirect on a timer (trying to find the shortest timing that made sure the request was sent), but that would be a bit of a hack and could easily vary from one browser to another.

The best solution would be for the server receiving the ajax call to return an immediate response (even if it isn't done with its own processing yet) and then you could just trigger the redirect upon receiving the response like this:

$.ajax({
    data: "type=userLoginLog&username=" + username, //Post Username
    url: environmentalVariables.support_api_address
}).then(function() {
    loginWithRefreshToken(refresh_token);
});

If the server is implemented properly, this should take only a smallish number of milliseconds to get the response.


You could even combine the two schemes above and trigger the redirect on the first action that completes (a timer or the ajax response):

function delay(x) {
    return new Promise(function(resolve) {
        setTimeout(resolve, x);
    });
}

var p = $.ajax({
    data: "type=userLoginLog&username=" + username, //Post Username
    url: environmentalVariables.support_api_address
});

// you will have to figure out what delay time is appropriate here
$.when(p, delay(200)).then(function() {
    loginWithRefreshToken(refresh_token);
})