Marreone
Marreone

Reputation: 117

Function to return variable from ajax call

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.

Upvotes: 4

Views: 3802

Answers (3)

Justin Ethier
Justin Ethier

Reputation: 134275

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.

Upvotes: 1

David Hogue
David Hogue

Reputation: 1831

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.

Upvotes: 3

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124888

That is because of the asynchronous nature of the AJAX query – the function returns before the response is back. To solve this, you must use the full fledged $.ajax() function and set async to false:

function GetText(getThis) {  
    var current = GetMarketAndLang();  
    var dataToReturn = "Error";  

    $.ajax({
        url: 'inc/ajaxGetText.php',
        type: 'GET',
        async: false,
        success: function(data) {
            dataToReturn = data;
        }
    });

    return dataToReturn;
}

This forces the script to wait until the request has returned before the execution of the script can continue, thus, the variable is now the one returned from the AJAX call.

Upvotes: 8

Related Questions