0

A common Asynchronous request is made by the following:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            abc = xhr.responseText;
        } else {
            console.error(xhr.statusText);
        }
    }
};
a = JSON.parse(abc);

I get the following error: Uncaught ReferenceError: abc is not defined

What is going wrong here?

Vasa
  • 45
  • 1
  • 8
  • 1
    Move `a = JSON.parse(abc);` in the `xhr.onload` success/OK condition. Also see [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tushar Feb 09 '16 at 04:29

1 Answers1

0

You are trying to call abc outside onload that might be the only issue.

 var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost:1337/test.php", true);
    xhr.onload = function (e) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                var abc = xhr.responseText;
                var a = JSON.parse(abc); // moved it here  
            } else {
                console.error(xhr.statusText);
            }
        }
    };

to return value from a function, Use it this way

function getResult(myFunction) {
     var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://localhost:1337/test.php", true);
        xhr.onload = function (e) {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var abc = xhr.responseText;
                    myFunction(abc);
                } else {
                    console.error(xhr.statusText);
                }
            }
        };
}

function myFunction(jsonData) {
 //do whatever you wish to do here
}

Now how you are going to call it.

getResult(myFunction); //callback;
zakaiter
  • 439
  • 3
  • 11