2

Hi there I am trying to return an object from the loadData function but I get "obj is not defined" in FF and "Uncaught ReferenceError" in chrome.I read that if you declare a variable without prefix "var it is assumed to be global"the scope of "obj" should be global and should return me the data from the json response.I have no idea where I am going wrong I am new to Javascript.Thanks for all the help.

function loadData()
{.....
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      personInfo=xmlhttp.responseText;
      obj = JSON.parse(personInfo);
      alert(obj[2].name);
    }
  };

  return obj;//"obj is not defined" in FF and "Uncaught ReferenceError" in chrome      

}



<h2>AJAX</h2>
<button type="button" onclick="loadData()">Request data</button>
<div id="myDiv"></div>

....

3 Answers 3

4

That's because the onreadystatechange function is asynchronous. You need to do something like:

function loadData(callback) {
  xmlhttp.onreadystatechange=function() {
    ...
    callback(data);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are returning obj from the loadData function, and when that function returns the obj is not yet defined. You need to do something with obj within the callback function itself - perhaps passing it to a third function that actually processes and does something with the data.

Comments

1

AJAX calls are async. The code won't wait for the response. It continues executing the next code while waiting for the response. This means that return obj is executed before it was actually filled with data.

what you should do is hand over a "callback", basically a function to execute when the data is received:

function loadData(callback){
    ...
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){

            //execute callback, passing it the parsed JSON
            callback(JSON.parse(xmlhttp.responseText));
        }
    } 
    //execute send here
}

//call loadData, passing it a callback function
//this function will be executed when response is received
//and the data will be provided as "returnedData"
loadData(function(returnedData){
    //use data
    alert(returnedData[2].name);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.