looping through json data in JavaScript - javascript

This is similar to this question, but I thought I'd reword it a bit differently in order to make myself more clear.
I have this json coming back from a $.ajax call:
{"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]]}
Q: In JavaScript, how do I parse through it to make a table such as:
<table>
<thead>
<tr>
<th>PersonID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1001</td>
<td>Scott</td>
<td>Wimmer</td>
</tr>
<tr>
<td>1002</td>
<td>Phillip</td>
<td>Senn</td>
</tr>
<tr>
<td>1003</td>
<td>Paul</td>
<td>Nielsen</td>
</tr>
</tbody>
</table>

var yourJson = {"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]];
var table = '<table>';
table += '<thead><tr><th>' + yourJson.COLUMNS.join('</th><th>') + '</th></tr></thead>';
table += '<tbody>';
for (var i=0;i<yourJson.DATA.length;i++) {
table += '<tr><td>' + yourJson.DATA[i].join('</td><td>') + '</td></tr>';
};
table += '</tbody>';
table += '</table>';

You can use client side templating engine such as jTemplates or pure to achieve it easily.

Related

How to fetch JSOn response into HTML table using pure JS?

This is HTML markup:
<table id="prodTable" class="table table-bordered" style="color:white">
<thead class="thead">
<tr class="font-weight-bold">
<th>No.</th>
<th>Name</th>
<th>Category</th>
<th>Slug</th>
<th>Price</th>
<th>GST Price</th>
<th>Keywords</th>
<th>Specification</th>
<th>Description</th>
<th>Attributes</th>
<th>Available Stock</th>
<th>Payment Method</th>
<th>Approval Status</th>
<th>Approve</th>
<th>Deal of the Day</th>
<th>Edit & Delete</th>
</tr>
</thead>
<tbody class="tbody">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><lable><input type="checkbox" id="approveProd" name="approval" value="approval">Approve</label></td>
<td><label><input type="checkbox" id="DealoftheDay" name="dealoftheday" value="dealoftheday">Deal of the Day</label></td>
<td><button class="btn btn-outline-info" type="button"><i class="fa fa-pencil-square"></i></button> <button class="btn btn-outline-danger" type="button"><i class="fa fa-trash"></i></button></td>
</tr>
</tbody>
</table>
and my js is
function getProductsData() {
var data = "";
var type = "application/x-www-form-urlencoded";
var url = "get_product_data";
var asyn = "true";
var method = "POST";
var respCallback = function(resp){
var proddata = JSON.parse(resp);
var table = document.getElementById('prodTable');
console.log(table);
for (var i = 0; i < proddata.length; i++) {
console.log(proddata[i]);
};
}
var res=serverRequest(data,method,url,asyn,type,respCallback);
}
the getProductsData() is a onload function written in the body and am getting the response as JSON.
I need to know how to populate the JSON response into the table. Am new to js and i dont need jquery code. Because am learning js.
Thanks in advance.
Here is the short example which will help you, how to append the json data in HTML Table.
Example :-
function append_json_data(data){
var table = document.getElementById('prodTable');
data.forEach((object) => {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.No + '</td>' +
'<td>' + object.Name + '</td>' +
'<td>' + object.Category + '</td>' +
'<td>' + object.Slug + '</td>';
'<td>' + object.GST_Price + '</td>';
table.appendChild(tr);
});
}
And further you can apply the td tag for other elements as well, As I am showing you how to append the data to HTML you can add the tag data after 'GST_Price' same as above.

tbody cant work in jquery

Why my tbody is not doing what I want, anyone can help me ?
This is my problem, in case I want to display in row but why that value just stay in column 1.2:
This is my jQuery:
$(function(){
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
success: function(response) {
console.log(response);
var counter = 0;
var obj = response.results;
var Content = ' ';
var x = 0;
Content += '<tbody>'; //opening tag tbody
for(var i=0;i<obj.length; i++)
{
Content += '<tr>';
Content += '<td>'+obj[i].name+'</td>';
Content += '<td>'+obj[i].height+'</td>';
Content += '<td>'+obj[i].hair_color+'</td>';
Content += '<td>'+obj[i].skin_color+'</td>';
Content += '<td>'+obj[i].eye_color+'</td>';
Content += '<td>'+obj[i].birth_year+'</td>';
Content += '<td>'+obj[i].gender+'</td>'
Content += '</tr>';
}
Content += '</tbody>';
$('#results').empty();
$('#results').append(Content);
}
});
});
var tbody=document.getElementById("results");
var table=document.getElementById("tableId");
var tbodyIndex= [].slice.call(table.tBodies).indexOf(tbody);
And this my html
<table class="table table-stripted table-bordered table-hover" id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
please help me , im newbie in javascript, oh yeah sorry for bad grammer, hope u guys help me , thank you
You don't have to add a tbody tag when your ajax response come in.
It's already in the DOM.
You can remove:
Content += '<tbody>';
Content += '</tbody>';
The HTML generated by your code is below.
Notice the two nested <tbody> elements, which disrupts the layout of your table.
GENERATED HTML
<table class="table table-stripted table-bordered table-hover " id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
<tbody>
<tr>
<td>Luke Skywalker</td>
<td>172</td>
<td>blond</td>
<td>fair</td>
<td>blue</td>
<td>19BBY</td>
<td>male</td>
</tr>
</tbody>
</tbody>
</table>
As Maarten van Tjonger has already answered, remove <tbody> from your Content string to avoid its duplication.
Rather than using empty() and append(), I've used html() to replace the contents of the <tbody> with the new HTML.
Also, you'll want to execute dataTable() on the <table> itself, not the <tbody>.
WORKING EXAMPLE
$(function() {
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
success: function(response) {
var obj = response.results,
Content;
for (var i = 0; i < obj.length; i++) {
Content += '<tr>';
Content += '<td>' + obj[i].name + '</td>';
Content += '<td>' + obj[i].height + '</td>';
Content += '<td>' + obj[i].hair_color + '</td>';
Content += '<td>' + obj[i].skin_color + '</td>';
Content += '<td>' + obj[i].eye_color + '</td>';
Content += '<td>' + obj[i].birth_year + '</td>';
Content += '<td>' + obj[i].gender + '</td>'
Content += '</tr>';
}
$('#results').html(Content);
$('#tableId').dataTable();
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-stripted table-bordered table-hover " id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
You are missing the quotes around your tbody id <tbody id=results> should be <tbody id="results"> and you are generating a second <tbody> in your JS which is not necessary. Otherwise your code runs fine so see this fiddle with the problems corrected.

JQuery: search and filter a table by a single column

I want to search a table by the values in a single column.
The table looks like this:
<table class="table main-content">
<thead>
<td><b>Title</b></td>
<td><b>Name</b></td>
<td><b>State (D)</b></td>
<td><b>Party</b></td>
<td><b>Room</b></td>
<td><b>Phone #</b></td>
<td><b>Special Role(s)</b></td>
</thead>
<tbody id="congress">
<tr>
<td>Senator</td>
<td>Alexander, Lamar</td>
<td>TN</td>
<td class="republican">Rep.</td>
<td>455 Dirksen</td>
<td>(202) 224-4944</td>
<td></td>
</tr>
<tr>
<td>Senator</td>
<td>Barrasso, John</td>
<td>WY</td>
<td class="republican">Rep.</td>
<td>307 Dirksen</td>
<td>(202) 224-6441</td>
<td></td>
</tr>
...
I want to be able to search the table by a given column, say names (index 1) or state (index 2). I've tried jets.js but it only allows one instance per page while I require at least two. JQuery is preferred, JS is fine, and external libs are ok but not optimal.
Cheers!
Edit:
I've tried using the following:
var $rows = $('#congress tr');
$('#stateSearch').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
The above code searches all of the columns in the table. How can I adjust it to search only for a specific column? (By index.)
The goal is to hide all of the tr that don't match the query in the given column
Something like this
function isFound(name, state)
{
$("table tbody").find("tr").each (function(){
var trElem = $(this);
if (($(this).find("td:eq(1) a").text() == name) && ($(this).find("td:eq(2)").text() == state))
return trElem;
})
return false;
}
Usage:
if (tr = isFound ('Firstname Lastname', 'State'))
tr.remove();
or, if you have more than one elements, use a loop for removing
while (tr = isFound ('Firstname Lastname', 'State'))
tr.remove();
Here's an example that will hide all rows where the State column (index 3) is TN. You can adapt it as you need:
$('td:nth-child(3)').each (function(){
if( $(this).val() == 'TN' )
$(this).parent().hide();
});
Another easy solution would be to use Datatables, which have a built-in search feature and methods to search by column. It may be overkill for your project, but take a look anyway for the future.
DataTables Example
You could reinvent the wheel, but it's probably better to just use DataTables unless you have an expressed need to do otherwise:
var $table = $('table');
// Setup - add a text input to each footer cell
$table.find('tfoot th').filter(':eq(1),:eq(2)').css('visibility', 'visible').each(function() {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
// DataTable
var table = $table.DataTable({
lengthChange: false
});
// Apply the search
table.columns().every(function() {
var col = this;
$('input', this.footer()).on('keyup change', function() {
if (col.search() !== this.value)
col.search(this.value).draw();
});
});
table tfoot tr th {
visibility: hidden;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/r-2.1.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/r-2.1.1/datatables.min.js"></script>
<table class="table table-striped main-content">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>State (D)</th>
<th>Party</th>
<th>Room</th>
<th>Phone #</th>
<th>Special Role(s)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Name</th>
<th>State (D)</th>
<th>Party</th>
<th>Room</th>
<th>Phone #</th>
<th>Special Role(s)</th>
</tr>
</tfoot>
<tbody id="congress">
<tr>
<td>Senator</td>
<td>Alexander, Lamar</td>
<td>TN</td>
<td class="republican">Rep.</td>
<td>455 Dirksen</td>
<td>(202) 224-4944</td>
<td></td>
</tr>
<tr>
<td>Senator</td>
<td>Barrasso, John</td>
<td>WY</td>
<td class="republican">Rep.</td>
<td>307 Dirksen</td>
<td>(202) 224-6441</td>
<td></td>
</tr>
</tbody>
</table>
try this:
var text = $(this).find('td:eq(1),td:eq(2)').text().replace(/\s+/g, ' ').toLowerCase();

append a table in javascript

i have a table that display data whenever a user clicks the start event button,but i need to know how to append the records when the user clicks the start button again,the previous record gets overridden
here is my javascript code
function DisplayData(downTime) {
console.log(downTime);
var newContent = '';
$.each(downTime.data, function (i, item) {
newContent += Hesto.Html.StartTR(item.downTime);
newContent += Hesto.Html.CreateTD(item.CategoryName);
newContent += Hesto.Html.CreateTD(item.StartTime);
newContent += Hesto.Html.CreateTD(item.EndTime);
newContent += Hesto.Html.CreateTD(item.Comments);
newContent = Hesto.Html.EndTR(newContent);
});
$('#DowntimeList').html(newContent);
}
and here is my html code:
<table id="Downtimetable" class="hesto">
<thead>
<tr>
<th>End Of DownTime</th>
<th>Category Name</th>
<th>Start Time</th>
<th>End Time</th>
<th>Comments</th>
</tr>
</thead>
<tbody id="DowntimeList">
</tbody>
<tfoot>
</tfoot>
</table>
Use append() instead of overwriting the html():
$('#DowntimeList').append(newContent);
As you suggested in the title of your question, append() it.
$('#DowntimeList').html(newContent);
Should be
$('#DowntimeList').append(newContent);
Simply use,
document.getElementById('DowntimeList').InnerHtml = document.getElementById('DowntimeList').InnerHtml+newContent

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