4

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.

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

-1 While it may make the code work, this is almost never the proper solution.
3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.