0

I feel like I've done everything right, but I get no response from my Ajax call, what am I missing?

function loadMedia() {

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon', true);
console.log(xhr.readyState);

xhr.onload = function() {
    if(xhr.status === 200 ) {
        console.log(true)
        let txt = JSON.parse(xhr.responseText);
        console.log(txt)
        for(let i in txt) {
            console.log(txt[i])
        }
    }
}
console.log(xhr.readyState)
xhr.send()
}

It just stays at readystate 1.

Adag89
  • 161
  • 10
  • 1
    Asynchronous vs synchronous. You are creating the XHR and starting it, then logging the ready state twice before the XHR has had an opportunity to do anything. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState –  Jan 15 '20 at 22:10
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Jan 15 '20 at 22:13
  • Btw, this is a pretty old way of doing things. Fetch API is the way to go now. –  Jan 15 '20 at 22:28

1 Answers1

0

xhr.readyState will not help you in the way that you wrote the code, you have to debug whether or not onload is called.

console.log(xhr.readyState); // sync
xhr.onload = function() {
   // async inside the function call, when onload
}; 
console.log(xhr.readyState) // sync, this isn't waiting AJAX response

If you put console.log(xhr.readyState) inside your callback fn it'll log other values, but remember to handle onerror as well...

I'd suggest you to use addEventListener listeners API instead of old fashion event handlers.

Hope it helps!

sminutoli
  • 853
  • 4
  • 11
  • I would suggest using `onreadystatechange` as the event to listen to. It specifically monitors the change in that property value. – Emiel Zuurbier Jan 15 '20 at 22:26
  • yeah, but the question here is why to observe the state change? it seems like he followed some old article... addEventListener('load') is what you need – sminutoli Jan 22 '20 at 18:13