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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With