How to wait for the ajax success handler to complete before another

I have the following script in my javascript:

  • Ajax is loading a record.
  • Based on the return value of this entry, another ajax call captures the html form that is added to the DOM
  • When # 2 is completed, records retrieved from # 1 are then uploaded to the form created in # 2.

I use when , so when # 2 is completed, I can load the form values ​​from # 1. The problem is that it seems that when the success handler does not wait for the completion, only the ajax call itself. I need to wait for the success function # 2 to complete (since this is what created the form in the DOM) before I can continue loading the form with values.

If I add alert1 in step 2, it works (which I assume because it is waiting for a warning to be clicked, and at this time the success handler has finished.

+5
source share
4 answers

Do something similar if you use nested functions in the success callback:

 $.ajax({ url: "somewhere" success: function(data1){ //Use data1 to determine ajax request #2 $.ajax({ url: "somewhere else" success: function(data2){ //Do stuff with data1 and data2 } }); } }); 
+3
source

You can use jQuery promises, ie:

 var loadingData = $.get(loadDataUrl); var loadingHtml = $.get(grabHtmlUrl); $.when(loadingData, loadingHtml).done(function(loadDataResult, loadHtmlResult){ //add the html to the dom //use data to update the dom as you please }); 

Note: $ .get is just a version of $ .ajax that executes a request to receive

Sources: http://api.jquery.com/deferred.promise/

http://api.jquery.com/jquery.get/

http://api.jquery.com/jquery.ajax/

http://api.jquery.com/jquery.when/

+1
source

You should not use when or success . It looks like (although the code examples would be clearer) you attach two separate listeners to the ajax call, but you want it to execute only after the other.
I would either throw both at the same event, for example:

 $.ajax( ... , function(){ // success // prep stuff here $.ajax( ... , function(){ // second success // do final stuff here }); }); 

Or wrap the ajax call in another promise (this might require a bit more reading around jQuery promises).

But if you do something like

 $.when($.ajax( ... , function(){ // thing a }).then(function(){ // thing b }); 

Thing a and b will be executed at the same time, because they are designed for almost the same thing.

+1
source

Bit late but

It is much better to use promises as the way they are intended to be used.

Pseudo implementation

 var promise = $.ajax({ url: url, data: data }).done(function (data) { var result = process(data); return $.ajax({ url: url, data: result }); }).done(function (data) { // data is the result of second ajax call }); 
0
source

Source: https://habr.com/ru/post/1214161/


All Articles