4

I'm not sure whether this has been asked before, the only similar item I found was this. Changing an alert() to a console.log() causes my code to fail. The 24th line (immediately after xmlhttp.send()) is the line that breaks, and I cannot figure out why.

function readFile()
{
var xmlhttp = new XMLHttpRequest();
var totalBudgeted = 0;
var totalSpent = 0;
var fileJSON = {};
var url = 'gamedata.json';

xmlhttp.onreadystatechange = function()
{
    if( xmlhttp.readyState == 4 )
    {
        //alert( 'XMLHttpRequest status code: ' + xmlhttp.status );
        // I am commenting this out so that I do not lose points for this assignment.  However, FireFox will return a status of 200 when serving a local file.
        //if( xmlhttp.status == 200 )
        {
            fileJSON = JSON.parse( xmlhttp.responseText );
        }
    }
}
xmlhttp.open( 'GET', url, true );
xmlhttp.send();

alert( fileJSON );
for( var key in fileJSON )
{
    if( fileJSON.hasOwnProperty( key ) )
    {
        alert( key + " -> " + fileJSON[key] );
    }
}
// Add up the column totals, and add the 'Total' row to fileJSON.
for( var rowCount in fileJSON )
{
    totalBudgeted += fileJSON[rowCount].budgeted;
    totalSpent += fileJSON[rowCount].spent;
    console.log( '!!!!!!!!!!!!!!!rowCount: ' + rowCount );
}
jsonToHtml( fileJSON );
}
Community
  • 1
  • 1
Adam Howell
  • 405
  • 10
  • 20

1 Answers1

6

putting the alert there obviously gives the asynchronous GET enough time to complete before you process the response

without the alert, your code processes fileJSON before it's even fetched

Jaromanda X
  • 47,382
  • 4
  • 58
  • 76