Displaying multiple json arrays with ajax/javascript - javascript

I'm having some issues displaying multiple JSON arrays if anybody could help,
i would appreciate it.
JSON
{
"houseOne": [
{
"name": "John Clarke",
"age": 22,
"dob": "19-11-90"
},
{
"name": "Mitch Woodier",
"age": 20,
"dob": "23-10-92"
},
{
"name": "Mavis Waddingham",
"age": 21,
"dob": "10-11-91"
}
],
"houseTwo": [
{
"name": "Luke Woodier",
"age": 22,
"dob": "19-11-90"
},
{
"name": "Rob Clarke",
"age": 20,
"dob": "23-10-92"
},
{
"name": "Alex Gayfag",
"age": 21,
"dob": "10-11-91"
}
]
}
Javascript
<script type="text/javascript">
function ajaxRequest(url)
{
var request = new XMLHttpRequest();
// Work around for IE caching problem
if (url.indexOf('?') < 0) {
today = new Date();
url += '?' + today.getTime();
}
request.open("GET", url, false);
request.setRequestHeader("Cache-Control", "no-cache");
request.send();
return request.responseText;
}
var data = ajaxRequest("results.json");
var houses = JSON.parse(data);
function displayJson() {
var myDiv =document.getElementById("content");
for (house = 0; house < 3; house++) {
var home = houses.houseOne[house];
myDiv.innerHTML += houseDetails(home,house);
}
}
function houseDetails(home,houseNumber){
var myHTML = "<h1>House Mate "+ (houseNumber +1)+"</h1>";
myHTML += "<table>";
myHTML += "<tr><th>Name</th><th>Age</th><th>D.O.B</th></tr>";
myHTML += "<tr>";
myHTML += "<td>";
myHTML += home.name;
myHTML += "</td>";
myHTML += "<td>";
myHTML += home.age;
myHTML += "</td>";
myHTML += "<td>";
myHTML += home.dob;
myHTML += "</td>";
myHTML += "</table>";
return myHTML
}
</script>
Basically I can get it to display houseOne as a table but I can't get it to display both houseOne and houseTwo, I hope this is clear I'm not very good with web dev.
Regards,
Dean

In your displayJson() function you're only referencing house.houseOne
var home = houses.houseOne[house];
Here's an updated version (I've added jQuery too) http://jsfiddle.net/XzZUR/1/
JSON
var houses = {
"houseOne": [{
"name": "John Clarke",
"age": 22,
"dob": "19-11-90"
}, {
"name": "Mitch Woodier",
"age": 20,
"dob": "23-10-92"
}, {
"name": "Mavis Waddingham",
"age": 21,
"dob": "10-11-91"
}],
"houseTwo": [{
"name": "Luke Woodier",
"age": 22,
"dob": "19-11-90"
}, {
"name": "Rob Clarke",
"age": 20,
"dob": "23-10-92"
}, {
"name": "Alex Gayfag",
"age": 21,
"dob": "10-11-91"
}]
};
Javascript
function displayJson() {
var myDiv = $("#content");
$.each(houses, function(){
var house = this;
$(house).each(function(key){
myDiv.append(houseDetails(this,key));
})
});
}

I'd recommend not using synchronous ajax request, it would be better to use a callback.
You could itterate through every house object like so:
function displayJson() {
var i,h,ret=[];
var myDiv =document.getElementById("content");
// houseone and housetwo
for (h in houses) {
// houseone and housetwo are arrays: [house,house,house]
// for every house in this array do:
for(i=0;i<houses[h].length;i++){
var home = houses[h][i];
ret.push(houseDetails(home,i));
}
}
//setting innerHTML is resource intensive
// no reason to do this within a loop.
myDiv.innerHTML=ret.join("");
}

Related

How to display nested JSON object in the form of table and rest JSON value as simple text

I want to display nested JSON objects.
This is what I have done so far:
orders = [
{ "custname": "Jack Smith", "mobile": "425361434", "location": "Sector 14", "slot": "12PM2PM", "value": 72.6, "items": [{ "prodcode": "PEP122", "quantity": 2 }, { "prodcode": "COK238", "quantity": 4 }] },
{ "custname": "Mary Gomes", "mobile": "723476123", "location": "Sector 22", "slot": "4PM6PM", "value": 130.60, "items": [{ "prodcode": "SUN677", "quantity": 2 }, { "prodcode": "LUX831", "quantity": 4 }, { "prodcode": "DET810", "quantity": 1 }] },
{ "custname": "Tim May", "mobile": "835099614", "location": "Pioneer Chowk", "slot": "Before 10AM", "value": 705, "items": [{ "prodcode": "GAR004", "quantity": 6 }, { "prodcode": "RB0277", "quantity": 3 }, { "prodcode": "MIR411", "quantity": 2 }] }
];
function showAllOrder() {
showtable();
}
function showtable() {
for (var i = 0; i < orders.length; i++) {
order = orders[i];
var str = "<div><div class='cell22' onclick=clicked(0)>Product</div>";
str = str + "<div class='cell22' onclick=clicked(1)>Qantity</div>";
var len = orders[i].items.length;
for (var j = 0; j < len; j++) {
for (var x = 0; x <)
//this value as simple text form above the table
var cost = ("Coustomer Name :" + order.custname);
var mob = (" Mobile :" + order.mobile);
var loc = (" Location :" + order.location);
var del = (" Delivery Slot :" + order.slot);
//this value in the form of table
var prod1 = "<div class='cell11'>" + orders[i].items[j].prodcode + "</div>";
var qty1 = "<div class='cell11'>" + orders[i].items[j].quantity + "</div>";
var row = "<div>" + cost + mob + loc + del + prod1 + qty1 + "</div>";
str = str + row;
}
}
var element = document.getElementById("mytable01");
element.innerHTML = str;
}

How to loop through jason data and display it in data list tag (dl)

I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

How to show html element as text in webpage

I want to loop this array and show the data into a table.
var dataM = [
{
"id": "1",
"name": "My #1",
"thumbnailUrl": "image/8.gif",
"price": 20
},
{
"id": "2",
"name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
"url": "image/10.gif",
"price": 10
}
];
Javascript function :
function loadData() {
var data = "";
for(var i = 0; i < dataM.length; i++) {
data += "<tr>";
var tempData = dataM[i];
Object.keys(tempData).forEach(function(key) {
data += "<td><code>" + tempData[key] + "</code></td>";
});
data += "</tr>";
}
var tbody = document.getElementsByTagName('tbody');
tbody[0].innerHTML = data;
}
How to show HTML element as text in webpage?
Create elements and use innerText attribute.
var dataM = [{
"id": "1",
"name": "My #1",
"thumbnailUrl": "image/8.gif",
"price": 20
},
{
"id": "2",
"name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
"url": "image/10.gif",
"price": 10
}
];
function loadData() {
var tbody = document.getElementsByTagName('tbody')[0];
for (var i = 0; i < dataM.length; i++) {
var tr = document.createElement('tr');
var tempData = dataM[i];
Object.keys(tempData).forEach(function(key) {
var td = document.createElement('td');
var code = document.createElement('code');
code.innerText = tempData[key];
td.appendChild(code);
tr.appendChild(td);
});
tbody.appendChild(tr);
}
}
loadData();
<table>
<tbody>
</tbody>
</table>

Output object array loop in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following code. I'm trying to output each key value ("company" and "address") the different "city1, 2 ,3" object (list goes on and on in the real example). in to a <p> using javascript. I am feeling a bit lost since I've tried a lot of different ways but I can't get it to work. I believe it might be due to the structure. If it would only be one city there would be no problem.
var data = {
"city1":
[
{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
},
{
"company": "Hemköp",
"address": "Allegatan 26"
}
],
"city2":
[
{
"company": "Ica Nära",
"address": "Centrumvägen 7"
}
],
"city3":
[
{
"company": "Hora brothers kiosk",
"address": "Rövsgatan 43"
},
{
"company": "Microsoft",
"address": "Husvägen 38"
}
]
};
You can iterate the data object using for...in and then iterate the array inside with forEach.
var body = '';
for(var city in data) {
data[city].forEach(function(entry) {
body += '<p>' + entry.company + ', ' + entry.address + '</p>';
});
}
console.log(body);
If it's reasonable within your product requirements, you might consider using list elements rather than a simple <p>. Try to use the appropriate document.createElement methods rather than building a string. Something like:
var data = {
"city1": [{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
}, {
"company": "Hemköp",
"address": "Allegatan 26"
}],
"city2": [{
"company": "Ica Nära",
"address": "Centrumvägen 7"
}],
"city3": [{
"company": "Hora brothers kiosk",
"address": "Rövsgatan 43"
}, {
"company": "Microsoft",
"address": "Husvägen 38"
}]
};
var cityList = document.getElementById("city-list");
for (var cityName in data) {
if (data.hasOwnProperty(cityName)) {
var city = document.createElement("li");
var cityLabel = document.createElement("p");
cityLabel.textContent = cityName;
city.appendChild(cityLabel);
var companyList = document.createElement("ul");
city.appendChild(companyList);
var companies = data[cityName];
for (var i = 0; i < companies.length; ++i) {
var company = document.createElement("li");
company.textContent = companies[i].company + ": " + companies[i].address;
companyList.appendChild(company);
}
cityList.appendChild(city);
}
}
<ol id="city-list"></ol>
Similar to Ben's answer. I personally like plain for..in loops over foreaches in javascript, but its a preference.
var data = {
"city1":
[
{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
},
{
"company": "Hemköp",
"address": "Allegatan 26"
}
],
...
};
var html = "";
for(var city in data)
{
//you can append the city to the html here if you want
// html += "<h2>" + city + "</h2>";
for(var company in data[city])
{
for(var field in data[city][company])
{
html += "<p>" + field + ": " + data[city][company][field] + "</p>";
}
}
}

How to store JSON data into JavaScript table format?

I am developing a web application and I use jQuery 1.5 and JavaScript for the main functionality of the app. I connect from my app to a RESTful interface where I GET information for a person.
I use this function to retrieve the information from the json page:
var jqxhr = $.getJSON("example.json", function() { // store the data in a table }
My data in json format are like but I will get as a result more than one persons having the format of:
[{"person":{"time":"2010-02-18T17:59:44","id":1,"name": "John","age":60, "updated_at":"010-02-18T17:59:44"}}]
How can I store only the id, the name and the age of the person in a JavaScript table (to be more precise an array) and ignore the rest of the information?
Here is the specific JavaScript / jQuery you need, based on the MAP function.
var originalData = [
{ "person": { "time": "2010-02-18T17:59:34", "id": 1, "name": "John", "age": 60, "updated_at": "010-02-18T17:59:41"} },
{ "person": { "time": "2010-02-18T17:59:44", "id": 2, "name": "Bob", "age": 50, "updated_at": "010-02-18T17:59:42"} },
{ "person": { "time": "2010-02-18T17:59:54", "id": 3, "name": "Sam", "age": 40, "updated_at": "010-02-18T17:59:43"} }
];
var data = $.map(originalData, function (ele) {
return { id: ele.person.id, name: ele.person.name, age: ele.person.age };
});
Here is a full example that will convert and display the results in HTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.6.1.js" type="text/javascript"></script>
<script type="text/javascript">
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + array[i][index] + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
$(document).ready(function () {
var originalData = [
{ "person": { "time": "2010-02-18T17:59:34", "id": 1, "name": "John", "age": 60, "updated_at": "010-02-18T17:59:41"} },
{ "person": { "time": "2010-02-18T17:59:44", "id": 2, "name": "Bob", "age": 50, "updated_at": "010-02-18T17:59:42"} },
{ "person": { "time": "2010-02-18T17:59:54", "id": 3, "name": "Sam", "age": 40, "updated_at": "010-02-18T17:59:43"} }
];
var data = $.map(originalData, function (ele) {
return { id: ele.person.id, name: ele.person.name, age: ele.person.age };
});
$('#results').append(CreateTableView(data, 'lightPro', true));
});
</script>
</head>
<body>
<div id="results" style="width: 500px; margin: 20px auto;">
</div>
You can use jQuery's map function:
var data = $.map(originalData, function(person) {
return { id: person.id, name: person.name, age: person.age };
});
map basically converts each item in an Array, producing a new Array with the modified objects.
$.getJSON("example.json", function(data) {
var name = data.person.name;
var id = data.person.id;
var age = data.person.age;
}
what do exactly mean by a javascript table
u can store in a html table by
var $table = $("<table>
<tr><td>name</td><td>"+name+"</td></tr>
<tr><td>id</td><td>"+id+"</td></tr>
<tr><td>age</td><td>"+age+"</td></tr>
</table>");

Categories

Resources