Reputation: 51
I am using the following code to run a query against the database that returns the information I want. I now want to display it on the screen.
function display(parsed) {
article = document.getElementById("homeArticle");
item = '<p>Something should go here</p>';
for (var i = 0; i < parsed.length; i++) {
var item = parsed[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
};
article.innerHTML = item;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(this.response)
var parsed = JSON.parse(this.responseText);
display(parsed.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
However this does not display the results on the screen. I used console.log to see if it was the getItems function that was not working but this logs the information I want so I am getting the correct information I just need it to display on the screen but i don't know why it is not?
below is what is logged in the console.
{"rows":[{"P_ID":"1","P_NAME":"Iphone 6","P_DESCRIPTION":"the latest iphone","P_PRICE":"300"},{"P_ID":"2","P_NAME":"Ipad Mini","P_DESCRIPTION":"the latest and smallest ipad","P_PRICE":"199.99"},{"P_ID":"3","P_NAME":"MacBook Pro","P_DESCRIPTION":"the macbook pro","P_PRICE":"999"},{"P_ID":"4","P_NAME":"Ipad Cover","P_DESCRIPTION":"a cover for ipad","P_PRICE":"30"},{"P_ID":"8","P_NAME":"Iphone 5c","P_DESCRIPTION":"the iphone 5c","P_PRICE":"150"},{"P_ID":"9","P_NAME":"Windows 8 laptop","P_DESCRIPTION":"a laptop with windows 8","P_PRICE":"250"}]}
Upvotes: 0
Views: 83
Reputation: 101700
It looks like you're passing the raw response text to your function instead of the parsed object.
Should be this:
xhr.onload = function() {
console.log(this.response)
var parsed = JSON.parse(this.responseText);
display(parsed); // <-----
};
There are also several issues in your display
function:
// v----- this said parsed instead of results
function display(results) {
article = document.getElementById("homeArticle");
item = '<p>Something should go here</p>';
for (var i = 0; i < results.length; i++) {
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
}
article.innerHTML = item; // needs to be innerHTML
}
Edit: Your array is on a property called rows
, so you either need to access this property when passing it into display()
:
display(parsed.rows);
Or access it inside your display()
function:
function display(response) {
var results = response.rows;
...
}
Upvotes: 1