0

I am struggling to get json object outside XMLHttpRequest.This is what I did:

    var ohl_json=[];
    var req = new XMLHttpRequest();
    req.responseType = 'json';
    req.open('GET', 'https://raw.githubusercontent.com/tekija/LCd/master/testSO.json', true);
    req.onload  = function() {
      var jsonResponse = req.response;
      ohl_json.push(jsonResponse)
    };
    req.send();
    console.log(ohl_json)

I get following output:

Array []
​
0: Object { type: "FeatureCollection", features: (960) […] }
​​
features: Array(960) [ {…}, {…}, {…}, … ]
​​
type: "FeatureCollection"
​​
<prototype>: Object { … }
​
length: 1
​
<prototype>: Array []

I tried to reference it with ohl_json[0] or ohl_json.features but no success. How can I access it? Any help is appreciated.

2 Answers 2

1

In your code snippet, you have set the 3rd parameter of req.open as true which means it will work asynchronously.

req.open('GET', 'https://raw.githubusercontent.com/tekija/LCd/master/testSO.json', true);

If you wrap your XMLHttpRequest into a promise and resolve with the response then you would be able to get the JSON outside the function.

function getResponse() {
   return new Promise(function (resolve, reject) {
     const req = new XMLHttpRequest();
     req.responseType = 'json';
     req.open('GET', 'https://raw.githubusercontent.com/tekija/LCd/master/testSO.json', true); // Third parameter is true which means request will work asyncronously.
   
     req.onload  = function() { 
       resolve(req.response);
     };
     
     req.send();
   });
}

getResponse()
.then(function(res) {
  console.log(res.features);
});

Sign up to request clarification or add additional context in comments.

4 Comments

Very clean and promising. But, how can I use res.features outside getResponse() function? I want to save it to global variable.
To use your global variable, you have to make sure your request has completed which is an async call. So your global var is dependent on this call. Can you explain a bit how do you use this variable?
Sure. Variable ohl_json is to be used later in code to generate Leaflet layer and show it on map.
If you want to use this feature as a global variable, I would suggest to use a state manager (Redux, Mobx, etc). Because this call is asynchronous and if you want to put it in a global variable then you have to wait till the response completed. So one option to call the getResponse where you want to use this value or another option to use a state manager.
1

A better way to do this:

async function getData(){
  const data =  await (await fetch('https://raw.githubusercontent.com/tekija/LCd/master/testSO.json')).json()

  console.log(data.features)
};

getData();

Doing this, you will acess the features object =)

6 Comments

Unfortunately, this is not working. I get Uncaught TypeError: can't access property 0, ohl_json[0] is undefined
Try this: let ohl_json = []; var req = new XMLHttpRequest(); req.open('GET', 'raw.githubusercontent.com/tekija/LCd/master/testSO.json', true); req.addEventListener('load', function(test){ ohl_json.push(req.responseText) }) req.send(); console.log(ohl_json)
It gets data, as array of text. i.e: "Array [ "{\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\" ". How can I parse this back to json format?
you can use JSON.parse() function - like this: let ohl_json = []; var req = new XMLHttpRequest(); req.open('GET', 'raw.githubusercontent.com/tekija/LCd/master/testSO.json', true); req.addEventListener('load', function () { ohl_json.push(JSON.parse((req.responseText))) }) req.send();
OK It works, but I again get an array with objects: Array [] ​ 0: Object { type: "FeatureCollection", features: (960) […] } ​ 1: 1 ​ length: 2
|

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.