0

I'm trying to return an object in the onreadtstatechange function when making an AJAX request. I assign the returned object to a variable, but when i try to access the variable, I get this error (after trying to use the description property of the object):

Uncaught TypeError: Cannot read property 'description' of undefined

Here is what I'm doing:

var myApp = function() {

 var obj1 = function() {
    return {
        something:function() {

            var xmlhttp;

            xmlhttp=new XMLHttpRequest();
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    return {
                        status:xmlhttp.status,
                        description:xmlhttp.responseText
                    }
                }
              }
            xmlhttp.open("GET","http://something",true);
            xmlhttp.send();

        }
    }
 }();

 var obj2 = function() {
    return {
        something2:function() {
            var something = obj1.something();
            console.log("Description: "+something.description + ", Status: "+something.status);
        }
    }
 }();

}();

Any suggestions?

A.Mokhtari
  • 451
  • 5
  • 16
mar_sanbas
  • 833
  • 2
  • 12
  • 20
  • 2
    [How to return the response from an AJAX call?](http://stackoverflow.com/q/14220321/) (the 2nd answer is edited for library-less Ajax) – Jonathan Lonowski Jul 28 '13 at 06:05
  • that link jonathan posted does sum it up pretty good – gezzuzz Jul 28 '13 at 06:09
  • store response in a variable `var data=xmlhttp.responseText` and then parse it `JSON.parse(data)` – HIRA THAKUR Jul 28 '13 at 06:14
  • Thanks Jonathan, I'm gonna try passing the callback to the function as the answer explains. The only problem is that my function has like 6 different states, so i'm gonna have to pass the 6 functions – mar_sanbas Jul 28 '13 at 13:03
  • I have one question. In the example i posted, how can I reference xmlhttp from function something2? I want to build the function in something2, and pass it to something, but I'm not sure how I'm suppose to reference xmlhttp.status from something2 – mar_sanbas Jul 28 '13 at 13:12
  • Sorry, I found the answer to that question in the other post – mar_sanbas Jul 28 '13 at 13:13

0 Answers0