This question has already been answered:

Good day! For example, given the function

function Test(){ var req = $ajax(...); req.done({function(responce){ console.log(responce); }); return ... }; 

In this case, the function will return something without waiting for the request to be executed and return readyState: 4; Actually the question is as follows. How to wait for readyState 4 before continuing after ajax?

Reported as a duplicate by members of Grundy , Pavel Mayorov , aleksandr barakin , Athari , cheops 24 Apr '16 at 5:35 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • No way, and it does not have to wait. When the readyState == 4 request is completed, the callback passed to the done function (if everything is fine) is completed and everything that needs to be done after the completion of the request can be done in it. - Grundy

1 answer 1

Solution (tested on jQuery 2.0.2 )

 $.ajax({ beforeSend: function (jqXHR, settings) { var self = this; var xhr = settings.xhr; settings.xhr = function () { var output = xhr(); output.onreadystatechange = function () { if (typeof(self.readyStateChanged) == "function") { self.readyStateChanged(this); } }; return output; }; }, readyStateChanged: function (xhr) { if (xhr.readyState == 4) { /* Do something */ } }, url: "..." });