Create multiple rows in HTML table using data from a JSON file - javascript

I'm trying to take data from a JSON file and create a html table, I am able to create the first row of the table using the below code:
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<table id='overview-table'>
<tr>
<th>owner Name</th>
<th>date</th>
<th>shares Held</th>
<th>shares Change</th>
<th>shares ChangePCT</th>
<th>market Value</th>
</tr>
<tr>
<td id='ownerName'></td>
<td id='date'></td>
<td id='sharesHeld'></td>
<td id='sharesChange'></td>
<td id='sharesChangePCT'></td>
<td id='marketValue'></td>
</tr>
</table>
<script type="text/javascript">
const requestUrl = 'https://api.npoint.io/b15e98da7b057152618b';
const requestJSON = async url => {
const response = await (await fetch(url)).json();
ownerName.innerHTML = response.ownerName[0];
date.innerHTML = response.date[0];
sharesHeld.innerHTML = response.sharesHeld[0];
sharesChange.innerHTML = response.sharesChange[0];
sharesChangePCT.innerHTML = response.sharesChangePCT[0];
marketValue.innerHTML = response.marketValue[0];
}
requestJSON(requestUrl);
</script>
</body>
</html>
The first row is created successfully, however if I want to include more rows then I would have to repeat the same bunch of code over again. Is there not a more efficient way of doing this?
Here is my JSON data:
{
"ownerName":{
"0":"VANGUARD GROUP INC",
"1":"BLACKROCK INC.",
"2":"BERKSHIRE HATHAWAY INC",
"3":"STATE STREET CORP",
"4":"FMR LLC",
"5":"GEODE CAPITAL MANAGEMENT, LLC",
"6":"PRICE T ROWE ASSOCIATES INC \/MD\/",
"7":"MORGAN STANLEY",
"8":"NORTHERN TRUST CORP",
"9":"BANK OF AMERICA CORP \/DE\/"
},
"date":{
"0":"09\/30\/2022",
"1":"09\/30\/2022",
"2":"09\/30\/2022",
"3":"09\/30\/2022",
"4":"09\/30\/2022",
"5":"09\/30\/2022",
"6":"09\/30\/2022",
"7":"09\/30\/2022",
"8":"09\/30\/2022",
"9":"09\/30\/2022"
},
"sharesHeld":{
"0":"1,272,378,901",
"1":"1,020,245,185",
"2":"894,802,319",
"3":"591,543,874",
"4":"350,900,116",
"5":"279,758,518",
"6":"224,863,541",
"7":"182,728,771",
"8":"176,084,862",
"9":"142,260,591"
},
"sharesChange":{
"0":"-4,940,153",
"1":"-8,443,132",
"2":"0",
"3":"-6,634,650",
"4":"6,582,142",
"5":"1,502,326",
"6":"-13,047,242",
"7":"278,206",
"8":"-3,744,060",
"9":"-6,873,324"
},
"sharesChangePCT":{
"0":"-0.387%",
"1":"-0.821%",
"2":"0%",
"3":"-1.109%",
"4":"1.912%",
"5":"0.54%",
"6":"-5.484%",
"7":"0.152%",
"8":"-2.082%",
"9":"-4.609%"
},
"marketValue":{
"0":"$192,498,204",
"1":"$154,352,894",
"2":"$135,374,643",
"3":"$89,494,673",
"4":"$53,087,679",
"5":"$42,324,666",
"6":"$34,019,605",
"7":"$27,645,036",
"8":"$26,639,879",
"9":"$21,522,605"
},

You can use a loop and duplicate a row template each time. Rather than using IDs for your table cells, you'll want to use classes as they'll be repeated throughout the document.
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<table id='overview-table'>
<tr>
<th>owner Name</th>
<th>date</th>
<th>shares Held</th>
<th>shares Change</th>
<th>shares ChangePCT</th>
<th>market Value</th>
</tr>
<tr id='rowTemplate'>
<td class='ownerName'></td>
<td class='date'></td>
<td class='sharesHeld'></td>
<td class='sharesChange'></td>
<td class='sharesChangePCT'></td>
<td class='marketValue'></td>
</tr>
</table>
<script type="text/javascript">
const requestUrl = 'https://api.npoint.io/b15e98da7b057152618b';
const requestJSON = async url => {
const response = await (await fetch(url)).json();
const limit = Math.max(...Object.keys(response.ownerName)) + 1;
for(let index = 0; index < limit; index++)
{
let newRow = rowTemplate.cloneNode(true);
newRow.id = '';
newRow.querySelector('.ownerName').innerHTML = response.ownerName[index];
newRow.querySelector('.date').innerHTML = response.date[index];
newRow.querySelector('.sharesHeld').innerHTML = response.sharesHeld[index];
newRow.querySelector('.sharesChange').innerHTML = response.sharesChange[index];
newRow.querySelector('.sharesChangePCT').innerHTML = response.sharesChangePCT[index];
newRow.querySelector('.marketValue').innerHTML = response.marketValue[index];
rowTemplate.parentNode.appendChild(newRow);
}
rowTemplate.parentNode.removeChild(rowTemplate); // Tidy up and remove the template
}
requestJSON(requestUrl);
</script>
</body>
</html>

Related

HTML/Javascript - Tables

Good day,
I want a straightforward way to loop through data and display it in a table.
If there's more data then it must create more rows etc.
Columns are fixed.. for now.
Example the code looks like the following
<table>
<thead>
<tr>
<th>Client Name</th>
<th>Client Representative</th>
<th>Client Representative Position</th>
<th>Client Representative Email</th>
<th>Date Created</th>
</tr>
</thead>
<tbody>
<tr>
<td id="client_name"></td>
<td id="client_representative"> </td>
<td id="client_representative_position"> </td>
<td id="client_representative_email"></td>
<td id="date_created"></td>
</tr>
</tbody>
</table>
<script>
var data = {
client_name: "Example Company",
client_representative: "John",
client_representative_position: "Engineer",
client_representative_email: "John#example.com",
date_created: "25/02/2021",
} **
document.getElementById("client_name").innerHTML = data.client_name;
document.getElementById("client_representative").innerHTML = data.client_representative;
document.getElementById("client_representative_position").innerHTML = data.client_representative_position;
document.getElementById("client_representative_email").innerHTML = data.client_representative_email;
document.getElementById("date_created").innerHTML = data.date_created; **
</script>
Basically, I want to avoid that piece surrounded by ** (javascript) bit by having it loop through the data.
Thanks in advance!
You Can use jQuery append()
Try this
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<table >
<thead >
<tr>
<th>Client Name</th>
<th>Client Representative</th>
<th>Client Representative Position</th>
<th>Client Representative Email</th>
<th>Date Created</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</body>
<script>
var data = [ {
client_name : "Example Company",
client_representative:"John",
client_representative_position:"Engineer",
client_representative_email:"John#example.com",
date_created:"25/02/2021",
},
{
client_name : "Example Company 2",
client_representative:"John 2",
client_representative_position:"Engineer 2",
client_representative_email:"John2#example.com",
date_created:"5/02/2021",
},
]
for (let index = 0; index < data.length; index++) {
var html = "<tr>";
html +="<td>"+data[index].client_name+"</td>";
html +="<td>"+data[index].client_representative+"</td>";
html +="<td>"+data[index].client_representative_position+"</td>";
html +="<td>"+data[index].client_representative_email+"</td>";
html +="<td>"+data[index].date_created+"</td>";
html += "</tr>";
$('#table-body').append(html);
}
</script>
</html>
To get the names of the keys in an object, you can use the in keyword.
This just loops through the keys as strings, allowing you to use in to set the elements in the table.
for (key in data)
document.getElementById(key).innerHTML = data[key]

TableSorter 2.0 No Parsers Detected

I am trying to make a table sort able with the TableSorter 2 package found here: https://mottie.github.io/tablesorter/docs/#Introduction. Ideally I would like to pull data from server, then update in real-time or have a click to sort option. Right now the data all populates, but when you click on the header the data isn't sorting. Am I missing something obvious?
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="/css/styles.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.min.js"></script>
<title>LTIIT Phone Status</title>
</head>
<body>
<div class='container'>
<table id="techtable"class="table tablesorter">
<thead>
<tr>
<th scope="col">User Name</th>
<th scope="col">Status</th>
<th scope="col">Queue</th>
<th scope="col">Call Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- Horizontal Line Divider -->
<hr>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/index.js"></script>
</body>
</html>
index.js
function getCurrentMembers() {
$.get('memberstatus', (data) => {
data.forEach(element => {
membername = element.username.replace('/','');
membername = membername.replace('-',"");
membername = membername.replace(' ','');
if (element.loggedin == 1) {
$("#techtable tbody").append(`
<tr id="${membername}row">
<td id="${membername}">${element.username}</td>
<td id="${membername}status" class="text-success">Online</td>
<td id="${membername}queue">${element.queue}</td>
<td id="${membername}callstatus">Ready</td>
</tr>`)
} else {
$("#techtable tbody").append(`
<tr id="${membername}row">
<td id="${membername}">${element.username}</td>
<td id="${membername}status" class="text-danger">Offline</td>
<td id="${membername}queue">Offline</td>
<td id="${membername}callstatus">Offline</td>
</tr>`)
}
});
});
$("#techtable").tablesorter({ debug:true });
}
$('document').ready(function(){
getCurrentMembers();
});
Error from Console
Detecting parsers for each column
jquery.tablesorter.min.js:1 No parsers detected!
jquery.tablesorter.min.js:1 Building cache for 0 rows (showing 0 rows in log) and 4 columns (0 ms)
Response from Network tab of Chrome to "memberstatus"
[{"username":"TestUser1","loggedin":1,"queue":"FirstResponder"},{"username":"TestUser2","loggedin":0,"queue":"OFFLINE"},{"username":"TestUser3","loggedin":1,"queue":"FirstResponder"},{"username":"TestUser4","loggedin":0,"queue":"TestQueue"},{"username":"TestUser5","loggedin":1,"queue":"TestQueue"}]
server.js NodeJS file
//.env file in parent directory that holds variable values - TO BE EXCLUDED FROM GIT!
require('dotenv').config();
//SQLite3 Requirements
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('UserStatus.db');
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS users (username TEXT,loggedin INTEGER, queue TEXT)");
});
//Express Web Server Requirements
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
//Start the server
const server = app.listen(process.env.Express_Port, () => console.log('Listening on port '+ process.env.Express_Port))
//Express Web uses
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname + '/public')));
//Express Get requests
app.get('/', (req,res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/memberstatus', (req,res) => {
//send back db information
db.all(`SELECT * FROM users`, (err,rows)=>{
if (err) throw err;
res.send(rows);
});
});
Right now the data all populates, but when you click on the header the data isn't sorting.
You may add sortlist property:
$("#techtable").tablesorter({ sortList: [[0,0], [1,0], [2,0], [3,0]] });
var data = [{"username":"TestUser1","loggedin":1,"queue":"FirstResponder"},{"username":"TestUser2","loggedin":0,"queue":"OFFLINE"},{"username":"TestUser3","loggedin":1,"queue":"FirstResponder"},{"username":"TestUser4","loggedin":0,"queue":"TestQueue"},{"username":"TestUser5","loggedin":1,"queue":"TestQueue"}];
data.forEach(element => {
membername = element.username.replace('/','');
membername = membername.replace('-',"");
membername = membername.replace(' ','');
if (element.loggedin == 1) {
$("#techtable tbody").append(`
<tr id="${membername}row">
<td id="${membername}">${element.username}</td>
<td id="${membername}status" class="text-success">Online</td>
<td id="${membername}queue">${element.queue}</td>
<td id="${membername}callstatus">Ready</td>
</tr>`)
} else {
$("#techtable tbody").append(`
<tr id="${membername}row">
<td id="${membername}">${element.username}</td>
<td id="${membername}status" class="text-danger">Offline</td>
<td id="${membername}queue">Offline</td>
<td id="${membername}callstatus">Offline</td>
</tr>`)
}
});
$("#techtable").tablesorter({ sortList: [[0,0], [1,0], [2,0], [3,0]] });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/css/theme.default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.min.js"></script>
<div class='container'>
<table id="techtable"class="table tablesorter">
<thead>
<tr>
<th scope="col">User Name</th>
<th scope="col">Status</th>
<th scope="col">Queue</th>
<th scope="col">Call Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- Horizontal Line Divider -->
<hr>
</div>
I noticed that in log it showed the data coming after the tablesorter function was called, even though it was called before.
I ended up change the .get call to .ajax and adding this complete option:
$.ajax({url: "/memberstatus", dataType : "json",contentType :"application/json",method:"GET", success: function(data){
console.log(data);
data.forEach(element => {
membername = element.username.replace('/','');
membername = membername.replace('-',"");
membername = membername.replace(' ','');
if (element.loggedin == 1) {
$("#techtable tbody").append(`
<tr id="${membername}row">
<td id="${membername}">${element.username}</td>
<td id="${membername}status" class="text-success">Online</td>
<td id="${membername}queue">${element.queue}</td>
<td id="${membername}callstatus">Ready</td>
</tr>`)
} else {
$("#techtable tbody").append(`
<tr id="${membername}row">
<td id="${membername}">${element.username}</td>
<td id="${membername}status" class="text-danger">Offline</td>
<td id="${membername}queue">Offline</td>
<td id="${membername}callstatus">Offline</td>
</tr>`)
}
});
}, complete: function(){
$("#techtable").tablesorter({ sortList: [[0,0], [1,0], [2,0], [3,0]],debug:true });
}});
}
Now works as expected. Thanks for your help.

Sort a table on clicking the header of each column using jQuery without duplicating the entire table

Trying to sort the table by just duplicating the row and not the entire table. On click of the column header that column's data must be compared and sorted and the rows rearranged , but I don't know where i am going wrong.Here is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Table Sort</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$('th').click(function() {
var ColNo = parseInt($(this).index());
var rows= $('tbody').children('tr');
var TotRows = parseInt(rows.length);
for (var i = TotRows-1; i >= 0; i--) {
for (var j = TotRows-1; j > 0; j--) {
var jint = parseInt(j);
var frstval = parseInt(rows[jint].getElementsByTagName("td")[ColNo].innerHTML);
var scndval = parseInt(rows[jint - 1].getElementsByTagName("td")[ColNo].innerHTML);
if (frstval < scndval) {
var a = frstval < scndval;
alert(a);
var sourceRow = $('tr').eq(jint);
alert(sourceRow);
var targetRow = $('tr').eq(jint-1);
targetRow.after(sourceRow.clone());
sourceRow.replaceWith(targetRow);
}
}
}
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>AAA</td>
<td>28</td>
</tr>
<tr>
<td>22</td>
<td>BBB</td>
<td>29</td>
</tr>
<tr>
<td>33</td>
<td>CCC</td>
<td>21</td>
</tr>
<tr>
<td>44</td>
<td>DDD</td>
<td>24</td>
</tr>
</tbody>
</table>
</body>
</html>
Better if you use a dhtmlXgrid... It's easier to implement, and you can create a JSON object of the entire dataset that you want to fill in the table. Then, just parse the JSON object into the dhtmlXgrid. With dhtmlXgrid, sorting, column size, column drag and drop, row drag and drop, etc., all such activities can be made automatically.

Changing value of a cell with JavaScript

I am having a problem changing the value of a cell in a HTML table. I am just messing around with JavaScript because I have never used it. Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var name = "Requiem";
var health = 100;
var strength = 1;
var agility = 1;
var intelligence = 1;
var gold = 50;
var Class = "Warrior";
document.getElementsByName('Name').innerHTML = name;
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Health</td>
<td>Strength</td>
<td>Agility</td>
<td>Intelligence</td>
<td>Gold</td>
<td>Class</td>
</tr>
<tr>
<td name="Name"></td>
<td name="Health"></td>
<td name="Strength"></td>
<td name="Agility"></td>
<td name="Intelligence"></td>
<td name="Gold"></td>
<td name="Class"></td>
</tr>
</table>
</body>
</html>
Your problem is two fold.
Your script tag is in the head and runs immediately. Only tags that have been processed before the script will be available to manipulate. You can fix this by moving your script tag below the <td name="Name"></td> tag or delaying the code with something like jQuery's document ready (requires jQuery).
document.getElementsByName returns a NodeList containing all the elements with the specified name. To manipulate the first element with this name, you can use document.getElementsByName("Name")[0].
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Health</td>
<td>Strength</td>
<td>Agility</td>
<td>Intelligence</td>
<td>Gold</td>
<td>Class</td>
</tr>
<tr>
<td name="Name"></td>
<td name="Health"></td>
<td name="Strength"></td>
<td name="Agility"></td>
<td name="Intelligence"></td>
<td name="Gold"></td>
<td name="Class"></td>
</tr>
</table>
<script>
var name = "Requiem";
var health = 100;
var strength = 1;
var agility = 1;
var intelligence = 1;
var gold = 50;
var Class = "Warrior";
document.getElementsByName('Name')[0].innerHTML = name;
</script>
</body>
</html>
document.getElementsByName() returns a NodeList (notice that it's Elements rather than Element, so you have to specify which element you'd like to modify.
In this case, there's only one element, so you only need to access the first in the list:
document.getElementsByName("Name")[0].innerHTML = name;
var name = "Requiem";
var health = 100;
var strength = 1;
var agility = 1;
var intelligence = 1;
var gold = 50;
var Class = "Warrior";
document.getElementsByName('Name')[0].innerHTML = name;
<!DOCTYPE html>
<html>
<body>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Health</td>
<td>Strength</td>
<td>Agility</td>
<td>Intelligence</td>
<td>Gold</td>
<td>Class</td>
</tr>
<tr>
<td name="Name"></td>
<td name="Health"></td>
<td name="Strength"></td>
<td name="Agility"></td>
<td name="Intelligence"></td>
<td name="Gold"></td>
<td name="Class"></td>
</tr>
</table>
</body>
</html>

How to get the data from API and put into tha table (Jquery)

Trying to store all the information that getting from JSONP in the table.
Have done the test with 'alert' to make sure that there are more info that only one line and can see that there are more info that one.
But when run it, in the table I can see title row and first row.
Can somebody correct my error?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.example.com/v1/deal/hotel?apikey=xxx&format=JSONP",
dataType : "jsonp",
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, value ) {
alert( index + ": " + value.StarRating + " , "+ value.Url);
});
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var to = parsed_json['Result'][0]['EndDate'];
document.getElementById("to").innerHTML = to;
var nights = parsed_json['Result'][0]['NightDuration'];
document.getElementById("nights").innerHTML = nights;
var currency = parsed_json['Result'][0]['CurrencyCode'];
document.getElementById("currency").innerHTML = currency;
var price = parsed_json['Result'][0]['Price'];
document.getElementById("price").innerHTML = price;
var link = parsed_json['Result'][0]['Url'];
document.getElementById("link").innerHTML = link;
//how to represent enlaces
var city = parsed_json['Result'][0]['City'];
document.getElementById("city").innerHTML = city;
var country = parsed_json['Result'][0]['CountryCode'];
document.getElementById("country").innerHTML = country;
var stars = parsed_json['Result'][0]['StarRating'];
document.getElementById("stars").innerHTML = stars;
}
});
});
</script>
</head>
<body>
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr>
<td id="from"></td>
<td id="to"></td>
<td id="nights"></td>
<td id="currency"></td>
<td id="price"></td>
<td id="link"></td>
<td id="city"></td>
<td id="country"></td>
<td id="stars"></td>
</tr>
</table>
</body>
</html>
The result of the Ajax callback is:
callback({"Errors":[],"Result":[{"FoundDate":"2013-12-04T16:11:36-08:00","CurrencyCode":"USD","NightDuration":"2.0","EndDate":"12/08/2013","Headline":"Cairo 5 Star Hotel, $36/night","IsWeekendStay":"true","Price":"36.0","StartDate":"12/06/2013","Url":"http‍://www.example.com/hotel/...&startDate=12/06/2013&endDate=12/08/2013&bid=0&sid=0","City":"Cairo","CountryCode":"EG","NeighborhoodLatitude":"30.0152","NeighborhoodLongitude":"31.1756","Neighborhood":"Cairo West - Giza","StarRating":"5.0","StateCode":"EG"},{"FoundDate":"2013-12-04T14:51:44-08:00",
If you have more than one line in result, then you have to -
Loop through it in the callback. You are not looping through it now. You are looping only for alert.
Dynamically create a new row in table for each line. You can clone the exiting tr for this using jquery clone method. But replace the id with 'class`.
Add data to that row pertaining to the line by modifying innerHtml of each td in the newly created row.
Finally, Append the row to the table
HTML -
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr class="first">
<td class="from"></td>
<td class="to"></td>
<td class="nights"></td>
<td class="currency"></td>
<td class="price"></td>
<td class="link"></td>
<td class="city"></td>
<td class="country"></td>
<td class="stars"></td>
</tr>
</table>
Javascript -
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, record ) {
$row = $('.first').clone();
var from = record['StartDate'];
$row.find('.from').html(from);
//Similarly repeat the above two lines for other columns
//...
$('#t').append($row);
});
}

Categories