Function to return a variable from an ajax call

I am trying to make a function returning a string from an 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 see that the ajax call is correct, but the whole function still returns the text "Error" instead of "and". Why is this and what can I do?

Thank.

+3
source share
3 answers

This is due to the asynchronous nature of the AJAX request - the function returns before the response is returned. To solve this problem, you should use the full feature $.ajax()and install asyncon 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 makes the script wait until the request is returned before the script completes, so the variable is now the one returned from the AJAX call.

+5

, AJAX .

function(data){  
    dataToReturn = data;  
}

, AJAX. return dataToReturn AJAX.

- , dataToReturn .

GetText, AJAX.

+3

An Ajax call is made asynchronously, so an β€œError” is returned immediately. To return ajax results, you need to use $ .ajax to execute a synchronous GET.

+1
source

Source: https://habr.com/ru/post/1727828/


All Articles