ChiranSJ
ChiranSJ

Reputation: 145

Creating An Array within AJAX Function Feeding Value Using For Loop

I have the following AJAX function that has 2 variables i.e. sTitle, sValue. I need these two variables to be added to an Array in the format of ArrayName[sTitle, sValue]. I have tried this using a for loop but couldn't get the result I expected. I'm hoping to use this array to draw a Google chart. The data source is an XML.

I'm trying to implement this For Loop and array within the AJAX Call.

So how can I solve this matter?

AJAX Function

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "ChartData.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('Pie').each(function() {
                var sTitle = $(this).find('Title').text();
                var sValue = $(this).find('Value').text();


            });
        },
        error: function() {
            alert("An error occurred while processing XML file.");
        }
    });
});

Upvotes: 0

Views: 65

Answers (1)

apsdehal
apsdehal

Reputation: 845

You can do it like this

var values = [];
function callback(val) {
   // Do something with the array here
};
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "ChartData.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('Pie').each(function() {
                var sTitle = $(this).find('Title').text();
                var sValue = $(this).find('Value').text();
                values.push([sTitle, sValue]);
            });
            callback(values);
        },
        error: function() {
            alert("An error occurred while processing XML file.");
        }
    });
});

Upvotes: 1

Related Questions