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

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.

Related

Wanted to display all the row data inside the table BY ID

I wanted to fetch multiple row data in a table by ID but this code throwing all rows. IDK how to do that please review my code and give feedback. And also I attached the output image which I'm getting. I want to display all the row data inside the table where is (शिर्षक डेबिट क्रेडिट) these topics. [1]: https://i.stack.imgur.com/cFo7b.png
----modal-----
<script>
$(document).ready(function() {
$('.view_btn').click(function(e) {
e.preventDefault();
var id = $(this).closest('tr').find('.id').text();
$.ajax({
type: "GET",
url: " {{ route('biniyojan_popup_details') }}",
data: {
'checking_viewbtn': true,
'id': id,
},
//success: function(response){
success: function(data) {
var html = '';
var biniyojan_popup_details = data.biniyojan_popup_details;
if (biniyojan_popup_details.length > 0) {
for (let i = 0; i < biniyojan_popup_details.length; i++) {
html += `
<table border="1" class="table table-hover table-wrapper-scroll-y my-custom-scrollbar">
<thead class="text-white bg-primary" style="font-size: 14px;">
<tr>
<th scope="col">S.N </th>
<th scope="col">मिति </th>
<th scope="col">आ.ब </th>
<th scope="col">स्रोत व्यहोर्ने संस्था</th>
</thead>
<tbody class="bbody" style="font-size: 14px;">
<tr>
<td>` + biniyojan_popup_details\[i\]\['biniyojan_id'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['date'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['ab'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['school'\] + `</td>
</tr>
</tbody>
</table>
<table id="example" border="1" style=" width:50% ; " class="table table-hover table-wrapper-scroll-y my-custom-scrollbar">
<thead class="text-white bg-primary" style="font-size: 14px;">
<tr>
<th>शिर्षक</th>
<th>डेबिट</th>
<th>क्रेडिट</th>
</tr>
</thead>
<tbody class="text-dark" style="font-size: 14px;">
<tr>
<td>` + biniyojan_popup_details\[i\]\['kriyakalap'\] + `</td>
<td id="bujet">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
<tr>
<td>` + biniyojan_popup_details\[i\]\['debit_credit_type'\] + `</td>
<td></td>
<td id="">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
<tr class="text-white bg-secondary" style="font-size: 14px;">
<td style="font-weight:bold;">Total</td>
<td style="font-weight:bold;">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
<td style="font-weight:bold;">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
</tbody>
</table>
`;
}
} else {
html += `
<tr>
<td colspan = "9" > Data not Found! </td>
</tr>
`;
}
$(".modal-body").html(html);
$('#exampleModalCenter').modal('show');
}
})
});
});
</script>
<!-- Modal Data -->][1]
----Controller-----
public function biniyojan_popup_details()
{
$biniyojan_popup_details = DB::table('biniyojan_details')
->leftJoin('biniyojan','biniyojan.biniyojan_id','biniyojan_details.biniyojan_id')
->get();
return response()->json(\['biniyojan_popup_details' => $biniyojan_popup_details\]);
}
Try this slight change. It adds a '=' to define what type of comparison we're making with biniyojan.biniyojan_id and biniyojan_details.biniyojan_id.
{
$biniyojan_popup_details = DB::table('biniyojan_details')
->leftJoin('biniyojan','biniyojan_details.biniyojan_id','=','biniyojan.biniyojan_id')
->get();
return response()->json(\['biniyojan_popup_details' => $biniyojan_popup_details\]);
}
You can try adding a where clause to your original code or try an alternative method using Models. This code works perfectly for me in my own project and I adapted it to your table names. I think you're trying to get details by an ID.
$biniyojan_popup_details = Biniyojan::where('biniyojan.biniyojan_id','=',$id)
->leftJoin('biniyojan_details','biniyojan.biniyojan_id','=','biniyojan_details.biniyojan_id')
->select('binoyojan_details.*','biniyojan.field1')
->get();

how can i get sum of one columns rows? [duplicate]

I am trying to add Price from table column to a total.
I am having problem adding values such as 10.00 or 5.99. I am able to calculate prices with int values, but not with values 10.00 or 5.99, etc.
Here is what I have below.
var table = document.getElementById("myTable"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseF(table.rows[i].cells[2].innerHTML);
}
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
</table>
<span id="val"></span>
You have three issues:
You are grabbing the wrong cell index, indices start at 0:
table.rows[i].cells[1]
You need to call the correct parse function:
parseFloat(table.rows[i].cells[1].innerHTML);
You need to format your output:
"SubTotal = $" + sumVal.toFixed(2);
Update: Added functionality for removing rows.
updateSubTotal(); // Initial call
function updateSubTotal() {
var table = document.getElementById("myTable");
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[1].innerHTML);
}, 0);
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
}
function onClickRemove(deleteButton) {
let row = deleteButton.parentElement.parentElement;
row.parentNode.removeChild(row);
updateSubTotal(); // Call after delete
}
#myTable td {
padding: 0.25em;
}
#val {
display: block;
margin-top: 0.5em;
}
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoodie</td>
<td class="count-me">15.00</td>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
</table>
<span id="val"></span>
You are accessing the incorrect array element and also need to use parseFloat
The cells array is zero-based so you need to use cells[1] to access the second column:
var table = document.getElementById("myTable"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseFloat(table.rows[i].cells[1].innerHTML);
}
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
</table>
<span id="val"></span>
updateSubTotal(); // Initial call
function updateSubTotal() {
var table = document.getElementById("myTable");
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[1].innerHTML);
}, 0);
let subTotal2 = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[2].innerHTML);
}, 0);
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
document.getElementById("val1").innerHTML = subTotal2.toFixed(2);
}
function onClickRemove(deleteButton) {
let row = deleteButton.parentElement.parentElement;
row.parentNode.removeChild(row);
updateSubTotal(); // Call after delete
}
#myTable td {
padding: 0.25em;
}
#val {
display: block;
margin-top: 0.5em;
}
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>M2</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoodie</td>
<td class="count-me">15.00</td>
<td class="count-me">34.00</th>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td class="count-me">22.34</th>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
</table>
<span id="val"></span>
<span id="val1"></span>
var cell = document.getElementsByClassName("count-me");
var val = 0;
var i = 0;
while (cell[i] != undefined) {
val += parseFloat(cell[i].innerHTML);
i++;
} //end while
document.getElementById("val").innerHTML = parseFloat(val).toFixed(2);
console.log(parseFloat(val).toFixed(2));
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr id="">
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td>
<button onClick="myFunction()">Remove</button>
</td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td>
<button onClick="myFunction()">Remove</button>
</td>
</tr>
</table>
<span id="val"></span>

Retain DOM values when removing rows from table with javascript

The issue I'm having is when I try to update the remaining rows in a table .outerHTML so that the name attributes are sequential. It's necessary as the .net backend expects the array to start at zero and be sequential.
If you have more than one row with entries, then delete a row, when updating the outerHTML the DOM values are removed and everything resets to blank. Is there a way to retain the values entered? It works fine not updating the outerHTML but that won't work for the backend.
https://jsfiddle.net/y2dxus1m/
function addBenefit() {
//gets the table and adds a new row based on length
var tableRef = document.getElementById('benefitsField').getElementsByTagName('tbody')[0];
var myHtmlContent = '<td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].FirstName"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].LastName"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].Amount"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].Source"></td><td><button class="btn btn-primary btn-sm" onclick="removeRow(this)">Remove</button></td>';
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
}
function removeRow(a) {
var row = a.parentNode.parentNode;
row.parentNode.removeChild(row);
var tableRef = document.getElementById('benefitsField').getElementsByTagName('tbody')[0];
for (var i = 0; i < tableRef.rows.length; i++) {
console.log(tableRef.rows[i].outerHTML)
//Issue is here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tableRef.rows[i].outerHTML = tableRef.rows[i].outerHTML.replace(/(\[).+?(\])/g, "[" + i + "]");
console.log(tableRef.rows[i].outerHTML)
}
}
<table class="deptTable" id="benefitsField">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Weekly Benefit Amount</th>
<th>Source</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="Octopus.Newborns.ReceivingBenefits[0].FirstName" /></td>
<td><input name="Octopus.Newborns.ReceivingBenefits[0].LastName" /></td>
<td><input name="Octopus.Newborns.ReceivingBenefits[0].Amount" /></td>
<td><input name="Octopus.Newborns.ReceivingBenefits[0].Source" /></td>
<td><button class="btn btn-primary btn-sm" onclick="removeRow(this)">Remove</button></td>
</tr>
</tbody>
</table>
<button onclick="addBenefit()">Add</button>
Adding the following function to reset the table rows after a row was removed resolved the issue. Fiddle updated
function setIndex() { $("td.index").each(function (index) { $(this).text(++index); }); }

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.

looping through json data in 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.

Categories