-4

This question is already answered and voted. My edits are related to making it clearer and share some new knowledge acquired for other developers, I'm not expecting new answers.

I'm reading an XML with jQuery, but when I try to show an alert it's fully working; however, when I try to return the value it always gives me a message that it's undefined.

function getText(value){

    var val;
    var lang;
    var location;
    lang=getLanguage();

    if (lang=='en')
        lang='';
    else
        lang+='.';

    location="resources/AppResources."+lang+'xml';

    $.get(location, function (xml) {
        $(xml).find("data").each(function () {
        
            var name=$(this).attr('name');

            if (name===value)
                return $(this).find('value').text();
        });
    });
    
}

This is the code that calls it:

$(document).ready(function() {  
    alert(getText('AppTitle'));
});

If I add an alert in the return statement it shows me the value selected.

Small update:

As Arun P Johny explained in his answer, the missed part in my code was the callback that are defined by Mozilla in this way:

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76

1 Answers1

1

You can't return a value from a async method, the easiest solution is to use a callback function like this one:

function getText(value, callback) {
    var val;
    var lang;
    var location;
    lang = getLanguage();

    if (lang == 'en') 
        lang = '';
    else 
        lang += '.';

    location = "resources/AppResources." + lang + 'xml';

    $.get(location, function (xml) {
        $(xml).find('data[name="' + value + '"]').each(function () {
            callback($(this).find('value').text());
        });
    });

}

$(document).ready(function() {
    getText('AppTitle', function(value){
        alert(value);
    })
});
Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531