mekk33
mekk33

Reputation: 130

Restrictions of Multiple AJAX Calls?

Context: I have a javascript file, within i have an AJAX function calling a php file returning the data and performing a function with it(an sql query returning records for a set date, then plotting it on a map using the google maps API). Lets call this Data A

Question: What i need is to be able to get the next days data and storing it in an array (Lets call it Data B) and comparing it with the first set of data(Data A). From my understanding i need another ajax call within this one, iv tried it but it seems i cannot get the data, i may have a misunderstanding of the core workings of ajax. For example:

var data_a;
var data_b;
    $.ajax({
         type: "POST",
         url: scriptday,
         data: $("#dayForm").serialize(),
         error: function( data ) {
              console.log("Error: "+ data );
         },
         success: function( json ) {
              data_a = json
                  //start of inner ajax call
                  $.ajax({
                           type: "POST",
                           url: scriptday2,
                           data: $("#dayForm").serialize(),
                           error: function( data ) {
                                console.log("Error: "+ data );
                           },
                           success: function( json ) {
                                data_b = json
                               // access data_a here
                           }
                       }    
                  });
                  //end of inner ajax call

        }    
    });

EDIT: Correct way of doing this was to store inner ajax call in a function that takes data_a inside.

function innerAjax(data_a){
    $.ajax({
       .....
       //data_a can now be used here
    })
}

and to call it inside the first ajax as

innerAjax(data_a);

this way using AJAX in a synchronous way :) thanks to those who contributed!

Upvotes: 2

Views: 108

Answers (1)

Bogdan Burym
Bogdan Burym

Reputation: 5512

No, restrictions of multiple AJAX calls do not exist, if you use async ajax (and looks like you do).

For you problem - perhaps you need to wait correctly for result of both ajax calls, to store the results and then process them.

Upvotes: 2

Related Questions