0

I´m having a problem retrieving a value from a XML file. I have an alert which gives me the expected value but when I try to return the value, it returns NaN. Thanks in advance.

function GetNumberOfSales(fixedScenario) {
    var result;
    $.ajax({
          type: "GET",
          url: "values.xml",
          dataType: "xml",
          success: function (xml) {        
            $(xml).find("values").each(function () {
                alert($(this).find(fixedScenario).text());
                result = $(this).find(fixedScenario).text();
            });
        }
    });
    return result;
}
freshbm
  • 5,540
  • 5
  • 46
  • 75
jose
  • 11
  • 2
  • 7

1 Answers1

1

You need to use:

var $xml = $(xml).parseXML();

And then use the jQuery's functions on the above object:

function GetNumberOfSales(fixedScenario) {
  var result;
  $.ajax({
    type: "GET",
    url: "values.xml",
    dataType: "xml",
    success: function(xml) {
      var $xml = $(xml).parseXML();
      $xml.find("values").each(function() {
        alert($(this).find(fixedScenario).text());
        result = $(this).find(fixedScenario).text();
      });
    }
  });

  // This executes before the AJAX call is completed.
  // This will NEVER work!
  // Please add the logic that uses the `result` here.
  return result;
}

Moreover, you cannot return a value from AJAX call, as it is asynchronous. Whatever you wanna do using the server response has to be done inside the success function and not elsewhere.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252