user5854440 user5854440 - 5 months ago 25
Ajax Question

Javascript: Am I using onreadystatechange properly?

Bare in mind I am very new to JavaScript syntax, so please have patience.

I'm trying to use multiple

onreadystatechange
's as promises to catch what I return from express, but every time I do, both of them are getting called. Here is my code:

var ready = function(){

xhr.open('GET', 'getallbeertypes');
xhr.send(null);
xhr.onreadystatechange = function () {

var parent = document.getElementById('recipes');
var docfrag = document.createDocumentFragment();

if(xhr.status == 200){
var beerTypes = JSON.parse(xhr.responseText);

//loop through beerTypes to append a button to each list item
for (var beer = 0; beer < beerTypes.length; beer++){
//create necessary elements
var li = document.createElement('li');
var button = document.createElement('BUTTON');

//set text content to list item
li.textContent = beerTypes[beer].alias;

//append list item to button
button.appendChild(li);

// add onclick attribute
button.setAttribute("name", beerTypes[beer]._id);
button.setAttribute("onclick", "moreInfo(this.getAttribute('name'))");

//append button to document fragment
docfrag.appendChild(button);
}

//display on DOM element
parent.appendChild(docfrag);
}else{
// console.log(JSON.parse(xhr.responseText));
var header = document.createElement('h1');
header.textContent = "Something went wrong. Please try again later.";
docfrag.appendChild(header);
parent.appendChild(header);
}
}
}
ready();


So the above section of code works, and it displays each JSON object as a button in a list of items. When the button is clicked, the following function is supposed to run:

var moreInfo = function(_id){
xhr.open('GET', '/getuserrecipes/' + _id);
xhr.send();
xhr.onreadystatechange = function(){
console.log("is this running?");
console.log(JSON.parse(xhr.responseText));
}
}


I'm expecting the
onclick
attribute should only run the
moreInfo
function.

Whenever I click one of the buttons, the
else
statement in the
ready
function is somehow running and displays
Something went wrong. Please try again later
on the screen.

The only connection I can make is the
onreadystatechange
, but I don't really know if that's it.

How/why is the other function even being called and How can I stop it? All help is appreciated.

Answer

You should check for the state of the request. To do that, use readyState property. There are 5 states, integers from 0 to 4, and you want the last one, which is 4.

something like this:

if (xhr.readyState == 4 && xhr.status == 200){
 ...
}

Check this example.