Jack Jack - 25 days ago 11
Ajax Question

Javascript Parsing of AJAX Requests


  1. Background: In the following client-side script, an AJAX request is sent to a server for data from a JSON file located on the server. The preferred approach is to send one request for all of the data required on the page as opposed to many individual requests for data throughout the page.

  2. Problem: Because AJAX requests run asynchronously, alert #2 at the bottom of the page runs while the page is loading while alert #1 located within the request runs after the page has loaded. As a result, the value for game.game_nb in alert #2 is 'undefined', while the value for game.game_nb in alert #1 contains valid data. Please note that the game object has functional scope.

  3. Question: How do I configure the AJAX request so that alert #2 has a value while the page is loading? I understand that one approach is to have an AJAX request each time the page needs data from the game object. I would prefer not to do this based on performance considerations and code readability. I have checked out other answers on stackoverflow, but none seem to address this specific concern.



Appreciate any thoughts or suggestions...

{ // loadGame
var request = new XMLHttpRequest();
path = setHTTPRequestPath( "loadGame" );
request.open("POST", path, true);
request.setRequestHeader("header_nb", "108");
request.setRequestHeader("header_nm", "loadGame");
request.setRequestHeader("game_nb", gameNumber);
request.setRequestHeader( "Content-Type", "application/json; charset=UTF-8" );
request.send(null);
request.onreadystatechange = function()
{
if (( request.readyState === 4 ) && ( request.status === 200 ))
{
game = JSON.parse(request.responseText, "utf8");
alert("alert #1: " + game.game_nb );
}
}
} // eofcb

alert("alert #2: " + game.game_nb );

Answer

Like you said it yourself, the JSON file resides at the server and game.game_nb is populated as a result of the request. So you'll not get the result at alert #2 because at that time the ajax request is still under process.

Once the ajax call is done, the dynamic function for, onreadystatechange will be invoked giving you the proper result for alert #1.

Remember the sequence in your code snippet is:

  • Send the ajax request.
  • Execute alert #2 (No value)
  • Receive response.
  • Execute alert #1 (with value)