I am reading a xml file and saving the data in array.But I am not able to use the array values later.I have declared everything as global. When I put an alert(myData[3]); I am getting "undefined".Please help.

Below is my code:

function modify_data(xml)
{
//alert("tyur");
$(xml).find('person').each(function(){
    phone = $(this).find('phone').text();
        email = $(this).find('email').text();
    name = $(this).find('name').text();
    myArray_name[n]= name;
    myData[n]=myArray_name[n];
       alert(myData[n]);
    n=n+1;
           });
alert(data);
alert(myData[3]);

}

Dani AI

Generated

Good catch by — the symptom you saw is typical when a loop index or array is left uninitialized or when you rely on implicit globals. Beyond fixing the immediate bug, a few small style changes make this pattern much more reliable and easier to debug.

Prefer explicit local declarations and array methods instead of managing a numeric counter by hand. Using push keeps indices contiguous and removes off-by-one issues; declaring variables with var/let prevents accidental globals. Also run parsing code inside the AJAX success handler (or after $.parseXML) so the xml object is guaranteed to be available, and use console.log instead of alert when inspecting arrays or objects.

Example pattern:

var names = [];

$(xml).find('person').each(function() {
  var nm = $(this).find('name').text();
  names.push(nm);
});

console.log(names[3]);

Additional notes and cautions: reset arrays before reusing them (names.length = 0) to avoid stale data; if you must use a numeric index, initialize it explicitly (var i = 0) and keep it scoped; avoid relying on alert to inspect complex values (use console.log(JSON.stringify(obj)) when needed). These changes prevent the kind of undefined entries that caused trouble for and reduce the chance of similar bugs later.

Recommended Answers

All 3 Replies

Did you remember to initialize n to zero somewhere? Did you remember to use dataType: "xml" in your jQuery ajax options?

Did you remember to initialize n to zero somewhere? Did you remember to use dataType: "xml" in your jQuery ajax options?

Thanks,
I forgot to initialize n to zero,now it is working.

Glad to help.

PS: Be sure to mark the thread as solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.