I'm wondering why this i+=1 doesn't increment the array by 1. When I click on the button the entire array length is shown. Can someone advise me what I'm doing wrong. I'm trying to load JSON data from WP related to posts with a certain category. This category I'm loading (http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12) has 2 posts total. When I console.log postsData.length, I get the value of 2. When I console log postsData I receive Object, Object Object, Object. These posts both load at the same time when the button is clicked, but I want the posts or each object to load 1 at a time. Below is the code:
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn){
portfolioPostsBtn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
//console.log(data);
createHTML(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
});
}
function createHTML(postsData){
var ourHTMLString = '';
// This for loop doesn't increment by 1
for (var i=0; i<postsData.length; i += 1){
console.log(postsData.length);
ourHTMLString += '<h2>' + postsData[i].title.rendered + '</h2>';
ourHTMLString += '<img class="gallery-test" src="' +postsData[i].acf.image + '"">'
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}
postsDataargument. Add it to your question. You can check if it is in fact an array withArray.isArray(postsData)Array.isArray(postsData)and receive true back. I added the other info to question.