0

I am aware this (or a similar) question has been asked a number of times. Still I do not understand how to get the loaded object outside of the scope of the function that creates it.

In particular if I do

var xmlhttp = new XMLHttpRequest();
var url = "lineJSON.json";
var myArr= new Array(); 

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myArr = JSON.parse(this.responseText);
        console.log(myArr[0].url); //here it give the right output
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
console.log(myArr[0].url); // Cannot read property 'url' of undefined

in the second console.log myArr is clearly not working, its url key it's undefined!

How do I make myArr available outside of that function ?

FYI the json is

[
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
}
]

If possible I would like to not use jQuery.

Rho Phi
  • 1,182
  • 1
  • 12
  • 21
  • The question this one is supposed to be a duplicate of, is about jQuery. The issue of `synchronous` request seems to be the same. – Rho Phi Sep 11 '16 at 21:03

1 Answers1

0

You can read property url, because it's undefined. It's undefined, becuse when you try acces to it array "myArr" is still empty. You using XMLHttpRequest asynchronously, so browser doesn't wait for response and executes next commands. You shulde use callback function or change

xmlhttp.open("GET", url, true);

to:

xmlhttp.open("GET", url, false);

But it's not the best solution. When request get error whole script will be stopped.

Tomek B.
  • 145
  • 5
  • Thanks for pointing the asynchronous implications. Indeed I checked it works with synchronous, but I want to explore the callback option. Thanks – Rho Phi Sep 11 '16 at 21:01
  • By the way, I am not sure there are many workaround to do it synchronous, maybe I am wrong. I am trying to load a JSON to have the code to understand what keys are present in it and populate a (search) form with those key name. If I do require to make the form, the file has to be already loaded ... am I missing something of the logic of JS ? – Rho Phi Sep 12 '16 at 07:26
  • Besides, my code loads the JSON into an object, which makes its content available once and for all for further processing. On the other hand, proceeding with processing as in the tutorials on [http://www.w3schools.com/json/json_http.asp](http://www.w3schools.com/json/json_http.asp) makes me load the file every time I have to process it ... not very efficient. – Rho Phi Sep 12 '16 at 07:28