I have a question about AJAX calls in jQuery
This is the problem I'm trying to solve:
- Call the server to get a list of codes
- For each code, call the server again to get the list of customers
- Display the result
I have a code snippet like this (it's almost a pseudo-code; just wanted to mention the parts of interest):
$('button#myButton').click(function() {
var codes = [];
var customers = [];
$.ajax({
// URL etc. Properties,
async: false
}).done(function(codes) {
// Update the values in the 'codes' array to be used later
});
// Use the 'codes' array to get the customers for each code
// and populate the 'customers' array
$(codes).each(function() {
$.ajax({
// URL etc. Properties,
async: false
}).done(function(customers) {
// Populate the 'customers' array
});
});
// Display the results (using both arrays) in a 'div'
});
Now, here's my problem:
At first, I wanted to do this thing using 2 nested getJSON calls, but no matter how hard I tried, I couldn't make it work (the second call waited for the first call to completely finish and then started the call)
Then, searching here, I saw that someone suggested to set the async function to false and it seems that now, the calls are behaving in the same order as the code
The only thing that I don't understand is that I receive a warning about Synchronous XMLHttpRequest on the main thread is deprecated and in jQuery's website, it's mentioned to use success/error/complete methods, but if I disable the async, then the order of the calls is messed up (at least I can't understand the order) and when I reach the second call, my codes array is empty, so there's nothing to do there!!!
Any help is appreciated because I spent a whole morning trying to make it work!
PS: As I said, the code is working, and I'm merely interested in the correct way to do it
Update
Thank you all for your answers. Maybe if I mention how I am supposed to display the result, it would make things more clear
I'm trying to display the results in a table with 'code', 'rate', and then 'customers'
When I'm finished with my first AJAX call, I have the values for my first two columns, so I can added the corresponding trs (and tds), but when I reach the second AJAX call, I have to go through each code to get the 'customers' for each code (from the server)
If I put all the logic into the second AJAX call's complete method, I have all the rows WITHOUT the third column, so I need to somehow add the customers to the last td on each row, which I don't know how!!!
async:falseshould never be done, and that's why the browser is telling you to stop doing it.async:falseis a terrible practice and has been deprecated by browser vendors.