views:

32

answers:

2

Hello, I have a function using $.ajax() to get values from an XML file, when the info is loaded and success event is fired, I use $(xml).find('').each(function(){}); to populate some vars...

function getData()
{
    $.ajax({
        type: 'GET',
        url : 'info.xml',
        dataType: 'xml',
        success: function(xml)
        {
            $(xml).find('DATAS').each(function()
            {
                date = new Date($(this).attr('DATE'));
                alert(date);
            })
                    //Here I have a bigger find/each that should take more time 
        },
            error: function()
            {
                    return false;
            }

    }); 
}

In this case, when I trigger the function from the document ready function, the alert shows the right data, but If I remove the alert from the function and try this instead, date wont be defined yet:

$(document).ready(function()
{
if(getData() != false)
{
    alert(date);

    }
});

I guess in this case the data is not ready yet? Is there a way to keep control on when the whole each() traversing is finished and ready?

+3  A: 

This happens because AJAX is asynchronous, meaning that the $.ajax() call doesn't finish until after the if() completes...the alert() in the way just gives it time to complete. You should kick off any operation that needs to use the data from inside the success callback, when it runs the data is then available. Something like this:

$(function() {
  getDataAndDoSomething();
  //other ready stuff...
});
function getDataAndDoSomething() {
  $.ajax({
    type: 'GET',
    url : 'info.xml',
    dataType: 'xml',
    success: function(xml) {
        $(xml).find('DATAS').each(function() {
            date = new Date($(this).attr('DATE'));
            alert(date);
        })
        //Do the other stuff depending on the date data
    }
  }); 
}
Nick Craver
Going to check this out, about the ajax: async I have already tried in the past and it can really frozen the browser.
Moustard
+4  A: 

.ajax() launches an asynchronous request, which means that getData() will return immediately. You have to do all kind of acting on the returned data within your success handler or, set the .ajax request to syncronous by adding

$.ajax({
   async: false   
});
jAndy
I would strongly advise against `async: false` whenever possible, this needlessly locks up the user's browser.
Nick Craver
@Nick: agreed 100%, but putting this into the answer might make things better to understand.
jAndy