tags:

views:

48

answers:

3

Hi,

Im trying to make a function return a string from a ajax call.

This is my code:

function GetText(getThis) {  
    var current = GetMarketAndLang();  
    var dataToReturn = "Error";  
    $.get('inc/ajaxGetText.php', {lang : current.lang, market : current.market, name : getThis},  
        function(data){  
            dataToReturn = data;  
    });  
    return dataToReturn;  
}

Using firebug i can see that the ajax call is correct but the whole function still returns the text "Error" instead of "and". Why is that and what can i do?

Thanks.

+4  A: 
Tatu Ulmanen
Thanks for a quick response!
Marreone
+2  A: 

That's because the AJAX call is asynchronous. Your

function(data){  
    dataToReturn = data;  
}

does not run until after the asynchronous AJAX call is completed. The return dataToReturn will actually execute before the callback function in the AJAX call.

The ideal way to do this would be to call the function that uses the dataToReturn from the callback.

Alternatively pass in a function to GetText to be executed when the AJAX call is complete.

David Hogue
+1  A: 

The ajax call is executing asynchronously, which is why "Error" is returned right away. To get the ajax results to return, you need to use $.ajax to do a synchronous GET.

Justin Ethier