views:

518

answers:

2

I have the following JavaScript (I'm using jQuery):

function language(language)
{
    var text = new Object();

    $.ajax({
     type: "GET",
     url: "includes/xml/languages/" + language + ".xml",
     dataType: "xml",
     success: function(xml){
      $(xml).find('text').each(function(){
       text[$(this).attr('id')] = $(this).text();
      });
     }
    });

    return true;
}

I have an XML file which is then being read by the class. The XML file has declarations like this:

 <text id="must_be_string">Must be a string.</text>
 <text id="must_be_number">Must be a number.</text>
 <text id="must_be_integer">Must be an integer.</text>

The XML file is being read correctly, but the problem I'm having is that the text variables don't seem to be working properly.

From putting some alert stop-points in to try to debug, I've discovered that this is what's happening:

Inside success: function(xml){, the var text can be properly accessed. However, the assignment inside that function to assign a new phrase to text doesn't add it correctly. Inside the success:, I can alert(text['must_be_string']) and get "Must be a string," but when I leave the Ajax call, it always shows "undefined."

In case I'm not being clear:

var text = new Object();

$.ajax({
 type: "GET",
 url: "includes/xml/languages/" + language + ".xml",
 dataType: "xml",
 success: function(xml){
  alert(text); // Shows [object Object]
  $(xml).find('text').each(function(){
   text[$(this).attr('id')] = $(this).text();
  });
  alert(text['must_be_string']); // Shows "Must be a string."
 }
});
alert(text['must_be_string']); // Shows undefined -- this is my problem

I would really, really appreciate any help on this. Please explain because I would really like to understand what's going on.

A: 

Variable 'text' lives in the scope of the 'language' function. I'm not sure how jQuery manages scopes, but I think the success function is a new function that is not inside 'language's scope.

'language' ends when reaching return and the ajax query is sent. However, the response comes afterwards (async).

Try declaring 'text' object as global, outside 'language'

Gerardo
+4  A: 

The success method of the ajax call is an asynchronous call. When you call $.ajax the method will instantly return and attempt to execute the alert(text['must_be_string']);, which won't be set until after the success of the ajax call is made, some point in the future.

Hope this helps.

bendewey
Thanks for pointing that out!I've fixed my problem by making this a synchronous request, i.e. adding "async: false," inside the $.ajax call.Thanks again!
Josh Leitzel
Glad I was able to help.
bendewey