0

Look at my code:

function dialogTexts() {
    var langText = $.ajax({
        type: 'GET',
        url: '/main/getdialogtexts',
        dataType: 'json'
    });

    langText.done(function(data) {  
        //data contains a array returned correctly from php            

        //The data.delete is returned correctly from php. data.delete contains a string 
        return data.delete; 
    });                        

    langText.fail(function(ts) {
        alert(ts.responseText);
    });
}

Why does the variable lang get undefined when calling above function?

var lang = dialogTexts();
bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72

1 Answers1

1

You can't return a value from an asynchronous ajax call. You can only get its value from a callback. Unless you use async:false which is not recommended because it freezes the UI while the request is pending.

See How do I return the response from an asynchronous call?

function dialogTexts(callback) {
    var langText = $.ajax({
        type: 'GET',
        url: '/main/getdialogtexts',
        dataType: 'json'
    });

    langText.done(function(data) {  
        //data contains a array returned correctly from php            
        callback(data.delete)
        //The data.delete is returned correctly from php. data.delete contains a string 
        return data.delete; 
    });                        

    langText.fail(function(ts) {
        callback(false);
    });
}

dialogText(function(text) {
    alert(text);
})
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • you mean `async:false` ? – andrew Mar 13 '14 at 20:47
  • Ok, thanks! Maybe I'm tired, but I don't quite understand how to return from the callback - function. I've tried to use a return inside the dialogTexts(function(text)) and then try var lang = dialogTexts() but of course that won't work. Your code works, but I want to store the returnvalue of callback into a variable. – bestprogrammerintheworld Mar 13 '14 at 21:05
  • @bestprogrammerintheworld See how you have two inner functions? You added return values for one of them but `dialogTexts` is not returning anything. Even if you tried to set a variable that you returned in `dialogTexts` from the inner handler, `dialogText` will have already returned by the time the callback is called and would have returned the value before the variable was set. – Ruan Mendes Mar 14 '14 at 01:48