0

enter image description hereI am having trouble storing the response of my XHR request.

Here is the javascript so far:

var req = new XMLHttpRequest;
req.open('get', 'https://jsonplaceholder.typicode.com/todos', true);
req.responseType = 'json';
req.send();

Over at chrome dev tools, i can see that response is the items i want so request should be fine. It is status of 200 and state 4.

The problem becomes when i try to write

var myJSON = req.response;

When i log this to console it responds with "null". But if i reassign the value through dev tools, to exactly the same value, i get my JSON object.. Can someone please explain to me why and how i can fix this?

1 Answer 1

1

try with ready state

   var req = new XMLHttpRequest;
    req.open('get', 'https://jsonplaceholder.typicode.com/todos', true);
    req.responseType = 'json';
    req.send();
    req.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          console.log(this.response);
var myJSON = this.response;
        }
      };
Sign up to request clarification or add additional context in comments.

4 Comments

I added this code snippet: ``` req.onreadystatechange = function(){ if(req.readyState === 4 && req.status === 200){ var myJSON = req.response; } } ``` Now its saying that myJSON is not defined o.O . Do u know what is wrong now?
I think u are trying to access myJSON outside the function
I added an image of the request if that helps you. I tried to see its content in dev tools to see if i can start working with it. I was trying to access it outside yes, i forgot the scope sorry for that. Is there a way i can have it outside to be able to work with it? Maybe declare it outside but assign value with the function?
It worked declaring the object, then assigning value the way u taught me, thanks alot again! And I appreciate the explanation! thanks one more time, was stuck at this for a while now :(

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.