1

I have two ajax calls in my javascript code. I have an array 'a' defined globally, which is modified by one of the ajax calls in 'success'. In the second ajax call's 'success', I want to make use of the updated array 'a', along with the data that i received from the second ajax call. It looks something like this :

var a = [];
x();
y();


function x(){
    //ajax call 1 - updates the array 'a' in its 'success'. Done async!

}
function y(){
        filters = []   //some filter
        $.ajax({
                type : 'POST',
                url : "get-other-data",
                dataType : 'json',
                async: "true",
                data:JSON.stringify(filters),
                contentType: 'application/json; charset=utf-8',
                success : function(data){

                    while(a.length == 0);
                    z(a,data);           // Want this to execute only after 'a' has been updated


                },
                failure: function(data){
                    alert('got an error');
                }
            });

}
function z(a,data){
  //does something
}

I tried doing the above in the second ajax call, but it runs into an infinite loop. I've confirmed that the first ajax call works perfectly. So, does this mean that it creates a copy of the global variable and doesn't update it even if other functions make an update? What changes do I do to make it work?

Thanks a lot in advance!

Phil
  • 157,677
  • 23
  • 242
  • 245
  • `return` the results from `$.ajax` (ie `return $.ajax(...)`) then you can do something like `x().done(y)` – Phil Jun 04 '20 at 04:57
  • Hey! wouldn't x().done(y) mean that execute y once x has executed completely? I want both the ajax calls to work together so that i can get the required data quickly, and then when i have the results from both the ajax calls, execute z(). I am a complete beginner, so please do pardon my mistakes. – Lakshya Bansal Jun 04 '20 at 06:23
  • 1
    Ah, try `$.when(x(), y()).done(z)`. Just make sure that `x` and `y` return the `$.ajax()` return value and that they resolve with the right data – Phil Jun 04 '20 at 06:34
  • That worked perfectly as expected. Thanks a lot – Lakshya Bansal Jun 05 '20 at 04:33

0 Answers0