j_dev j_dev - 18 days ago 5
Ajax Question

Alternative to "async: false" for successive AJAX calls

In the code snippet below, I am using two AJAX GET request to grab data from two different sources. In each request I parse the response data, create a temporary array with the relevant data each item, and push this temporary array into a master array. However, this only works if I include "async: false" in the AJAX request, which is now deprecated. Is there an alternative way I could write this code? (NOTE: Although I am using two AJAX requests in this code snippet, I will probably need to use a total of four in the project I am working on).

function get_results() {
$(document).ready(function() {
var master_array = [];
$.ajax({
type: "GET",
url: "http//:www.source1.com",
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find('product').each(function() {
var Average = $(this).find('Average').text();
var Price = $(this).find('Price').text();
var Name = $(this).find('Name').text();
var Url = $(this).find('Url').text();
var Image = $(this).find('Image').text();
master_array.push([Average, Price, Name, Url, Image]);
});
}
});
$.ajax({
type: "GET",
url: "http//:www.source2.com",
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find('product').each(function() {
var Average = $(this).find('Average').text();
var Price = $(this).find('Price').text();
var Name = $(this).find('Name').text();
var Url = $(this).find('Url').text();
var Image = $(this).find('Image').text();
master_array.push([Average, Price, Name, Url, Image]);
});
}
});
});
}

Answer
function get_results() {
  $(document).ready(function() {
    var master_array = [];

   function MyFirstFunction = $.ajax({
      type: "GET",
      url: "http//:www.source1.com",
      dataType: "xml",
      success: function(xml) {
        $(xml).find('product').each(function() {
          var Average = $(this).find('Average').text();
          var Price = $(this).find('Price').text();
          var Name = $(this).find('Name').text();
          var Url = $(this).find('Url').text();
          var Image = $(this).find('Image').text();
          master_array.push([Average, Price, Name, Url, Image]);
        });
      }
    });

    function MySecondFunction = $.ajax({
      type: "GET",
      url: "http//:www.source2.com",
      dataType: "xml",
      success: function(xml) {
        $(xml).find('product').each(function() {
          var Average = $(this).find('Average').text();
          var Price = $(this).find('Price').text();
          var Name = $(this).find('Name').text();
          var Url = $(this).find('Url').text();
          var Image = $(this).find('Image').text();
          master_array.push([Average, Price, Name, Url, Image]);
        });
      }
    });
  });
}

  MyFirstFunction().done(MySecondFunction);