XMLHTTPRequest is not defined

I’m just starting with WordPress Rest API, using this tutorial, trying to read JSON using ajax

var postsBtn = document.getElementById(‘posts-btn’);
var postsContainer = document.getElementById(“posts-container”);

if (postsBtn){
postsBtn.addEventListener(“click”, function(){
console.log(“clicked”);

var ourRequest = new XMLHttpRequest();
ourRequest.open(‘GET’, ‘http://localhost:8888/wordpress/wp-json/wp/v2/posts’);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
console.log(data);
} else {
console.log(“We connected to the server, but it returned an error.”);
}
};

ourRequest.onerror = function() {
console.log(“Connection error”);
};

ourRequest.send();

});
}

When I click the button I get XMLHTTPRequest is not defined How to fix that? I have WordPress version 4.9.6

Read more here:: XMLHTTPRequest is not defined

Leave a Reply

Your email address will not be published. Required fields are marked *