0

I have some problem with transfer of variable outside the function. It's seems to be very simple but I have some problem with it.

var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);

function XHRhandler() {

    if (xhr.readyState == 4) {

        var json;
        if (JSON && JSON.parse) {
            json = JSON.parse(xhr.responseText);
        } else {
            eval("var json = " + xhr.responseText);
        }
        console.log(json);
        myJson= json;
        xhr = null;
    }

}
console.log(myJson);

What I need is to pass the data from local variable json to global myJson; But when i do console.log(myJson) i get undefined. What is the problem?

Thank you

Karb
  • 327
  • 3
  • 12
  • 1
    It is undefined since `console.log(myJson);` executes immediately without waiting for xhr to complete. XHRhandler will be called only when the data arrived from the server. – Fizer Khan Mar 12 '14 at 09:33
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Mar 12 '14 at 09:42
  • You can also try `promise` and set variable in its callback. – Mithlesh Kumar Mar 12 '14 at 12:41

2 Answers2

0

Try moving the statement console.log(myJson); inside your if condition or alternately initialize your variable with some value. It seems your statement is getting called before it is getting populated with any value.

ManeetK
  • 675
  • 1
  • 5
  • 11
0

The XMLHttpRequest is async so it is not done yet when you try to write the myJson variable to console. Wrap it in a function and call that function after the XMLHttpRequest is completed instead.

var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);

function XHRhandler() {

    if (xhr.readyState == 4) {

        var json;
        if (JSON && JSON.parse) {
            json = JSON.parse(xhr.responseText);
        } else {
            eval("var json = " + xhr.responseText);
        }
        console.log(json);
        myJson= json;
        xhr = null;
        writeToConsole();
    }

}

function writeToConsole() {
    console.log(myJson);
}
Johan
  • 1,016
  • 7
  • 13