an empty table. To fill the product table, its content should be created dynamically by using JavaScript to insert the data into the table. The data should be requested from the webserver. You should first send an AJAX GET request to the Web service. When this request returns successfully, you should insert the returned JSON data into your table using the DOM
You can try datatable plugin to fullfill your scenario
to work with this your data should be in the format of
{ "draw": 1, "recordsTotal": 57, "recordsFiltered": 57, "data": [
[
"Airi",
"Satou",
"Accountant",
"Tokyo",
"28th Nov 08",
"$162,700"
],
[
"Angelica",
"Ramos",
"Chief Executive Officer (CEO)",
"London",
"9th Oct 09",
"$1,200,000"
],
]
}
HTML CODE
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<table>
JS CODE:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "../server_side/scripts/server_processing.php"
} );
} );
include below scripts too
https://code.jquery.com/jquery-3.3.1.js
https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js
You can append the dynamically created html using innserHTML property ofDOM element.
Example
fetch('<some URL>')
.then((response) => {
let data = response.json(); // Let supposed the data is in this format [{ id: 1 }, { id: 2 }, { id: 3 }]
let tr = '';
data.forEach(function(value) {
tr += `<tr><td>${data.id}</td></tr>`;
});
document.querySelector('#table_id tbody').innerHTML = tr; //Append the data
}).catch(error => {
console.log(error);
});
Or use document.createElement to create the element and then append it to the DOM
fetch('<some URL>')
.then((response) => {
let data = response.json(); // Let supposed the data is in this format [{ id: 1 }, { id: 2 }, { id: 3 }]
let tr = '';
let tableBody = document.querySelector('#table_id');
data.forEach(function(value) {
let tr = document.createElement('tr');
tr.textContent = data.id
tableBody.appendChild(tr);
});
}).catch(error => {
console.log(error);
});
HTML
<table id="table_id">
<tbody>
</tbody>
</table>
Related
I want to ask how can I insert my sql query to the html datatable table body.
This is my present code:
AJAX Query for loading datatable after button click:
$(document).on('click','#filtersearch',function(e){
e.preventDefault();
$.ajax({
url:"index.php",
method:"POST",
data:{
formula:"filtersearch"
},
dataType:"json",
beforeSend:()=>{
$('.load_spinner').removeClass('d-none');
},
success:function(res){
$('.load_spinner').addClass('d-none');
select_d = res;
console.log(res);
var str ="";
if (!$.isEmptyObject(select_d)) {
select_d.forEach((x)=>{
str += `<tr>
<td>${x.assetid}</td>
<td>${x.assetcode}</td>
<td>${x.assetserial}</td>
<td>${x.assetname}</td>
<td>${x.assettype}</td>
<td>${x.assetcat}</td>
<td>${x.dpurchased}</td>
<td>${x.price}</td>
<td>${x.dperiod}</td>
<td>${x.finprice}</td>
<td>${x.status}</td>
<td>${x.assetage}</td>
<td>${x.location}</td>
</tr>`;
})
}
data_table("#table_index","#tbody_index",str);
}
})
})
Javascript for Datatable Content transfer from AJAX:
function data_table(table_name,tbody_name,data_tbody) {
$(table_name).DataTable().destroy();
$(tbody_name).empty().html(data_tbody);
$(table_name).DataTable();
};
Datatable HTML cointainer that will get the ajax query:
<table class="table table-bordered" id="table_index" width="100%" cellspacing="0">
<thead>
<tr>
<th>No.</th>
<th>Asset Code</th>
<th>Asset Serial</th>
<th>Asset Name</th>
<th>Category</th>
<th>Type</th>
<th>Date Purchased</th>
<th>Initial Price (PHP)</th>
<th>Depreciation Period</th>
<th>Final Price (PHP)</th>
<th>Status</th>
<th>Classification</th>
<th>Location</th>
</tr>
</thead>
<tbody id="tbody_index">
</tbody>
</table>
PHP code for database query:
<?php
include 'include/dbconfig.php';
$sql = 'SELECT * FROM tbl_assets';
$result = mysqli_query($conn, $sql);
$formula ='';
if (isset($_POST['formula'])) {
$formula = $_POST['formula'];
}
switch ($formula) {
case 'filtersearch':
$result = filtersearch();
$supData = array();
while ($row = $result->fetch_assoc()) {
$supData[] = $row;
}
echo json_encode($supData);
break;
default:
break;
}
function filtersearch()
{
include 'include/dbconfig.php';
$query = mysqli_query($conn,"SELECT * FROM tbl_assets");
return $query;
}
?>
I just want to ask what is wrong with my code since the script doesn't show the values of Tbody as intended. Thanks.
I found a solution after manipulating the pages instead.
Instead of coding all of them in one page, I tried creating another page (switchcase.php) that contains the PHP files and it worked as intended.
Just a hunch, but I think ajax doesn't accept urls of the same page. I don't know if thats how it works but yeah, I changed the url to switchcase.php and it worked.
if you using datatable with ajax and php try this way
<script>
$(function(){
$('#table_index').dataTable( {
'lengthMenu': [[10, 25, 50, 100, 500], [10, 25, 50, 100, 500]],
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'order': [[ 1, "desc" ]],
'ajax': {
'url': 'index.php'
},
"columns": [
{ "data": "id" },
{ "data": "asset_code" },
{ "data": "asset_serial" ,'bSortable': false},
{ "data": "asset_name" ,'bSortable': false},
{ "data": "category_id" ,'bSortable': false},
{ "data": "type", 'bSortable': false},
{ "data": "date_purchased"},
{ "data": "initial_price" },
{ "data": "depreciation_period" },
{ "data": "final_price" },
{ "data": "status" ,'bSortable': false},
{ "data": "classification" },
{ "data": "location" }
]
});
$.fn.dataTable.ext.errMode = 'none';
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover table-nomargin table-condensed" id="table_index">
<thead>
<tr>
<th>No.</th>
<th>Asset Code</th>
<th>Asset Serial</th>
<th>Asset Name</th>
<th>Category</th>
<th>Type</th>
<th>Date Purchased</th>
<th>Initial Price (PHP)</th>
<th>Depreciation Period</th>
<th>Final Price (PHP)</th>
<th>Status</th>
<th>Classification</th>
<th>Location</th>
</tr>
</thead>
<tbody></tbody>
</table>
I'm having trouble with displaying my json data correctly. I want to get each products and place them into it's own row.
The problem now is that it places all the data of for example the value "name" into one table row instead of multiple rows.
This is my json data
{
id: "FVFkkD7s8xNdDgh3zAyd",
name: "AlperKaffe",
products: [
{
id: "0cfBnXTijpJRu14DVfbI",
name: "Første Kaffe",
price: "1",
size: "small",
quantity: "20 ml"
},
{
id: "JQadhkpn0AJd0NRnnWUF",
name: "Anden Kaffe",
price: "2",
size: "Medium",
quantity: "25 ml"
},
{
id: "UwHHdH8bFxbVHkDryeGC",
name: "kaffeeen",
price: "300",
size: "Small",
quantity: "23 ml"
},
{
id: "WiX5h0wFMNkCux9cINYq",
name: "kaffe modal",
price: "230",
size: "Medium",
quantity: "39 ml"
},
this is my Js file which gets the json data. As you can see i'm only working with the "name" value for now
// Jquery getting our json order data from API
$.get("http://localhost:8888/products", (data) => {
let rows = data.map(item => {
let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
let productsName = item.products.map(prod => `${prod.name}`);
$clone.find('.name').html(productsName);
return $clone;
});
// appends to our frontpage html
$("#frontpage_new_ordertable tbody").append(rows);
});
this is my html file
<body>
<table id="frontpage_new_ordertable">
<tbody>
<tr>
<th>Name</th>
<th>Price</th>
<th>Size</th>
<th>Quantity</th>
<th></th>
</tr>
</tbody>
<tfoot>
<tr>
<td class="name"></td>
<td class="price"></td>
<td class="size"></td>
<td class="quantity"></td>
<td class="buttons"></td>
</tr>
</tfoot>
</table>
<script src="./itemPage.js"></script>
</body>
you must replace
let rows = data.map(item => {
to
let rows = data.products.map(item => {
and
let productsName = item.products.map(prod => `${prod.name}`);
to
let productsName = item.name;
https://jsfiddle.net/ab7t1vmf/3/
The issue in your JS snippet seems to be let rows = data.map(item => { ...
From what you describe, the JSON data is comprised of 3 keys:
id
name
products
You cannot execute a map function directly on a Javascript Object, this function requires an array.
Looking a bit more at your code, I understand you need to display each product on its own row. Thus, you would need to use the map function on data.products which contains an array (of products).
let rows = data.products.map(item => {
// ...
$clone.find('.name').html(item.name);
// ...
// ...
});
Reference: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map
I would like to display items belonging to different customers. To this effect, i am fetching data through an ajax call and therefater grouping the data based on each unique customer. I then append the grouped data to my html.
Structure of my grouped data looks like:
"John Doe": [
{
"Item_id" : 1
"Item_name": "abc"
},
{
"Item_id" : 2
"Item_name": "def"
},
],
"Jane Doe":
{
"Item_id" : 3
"Item_name": "ghi"
},
{
"Item_id" : 4
"Item_name": "jkl"
},
]
My code looks like:
$.each(groupedData, function (key, value) {
$('.cust_items').append(`
<h4 class="mb-0"> ` + key + `</h4>
<table id="dataTable">
<thead>
<th>Item No.</th>
<th>Item Name</th>
</thead>
<tbody></tbody>
</table>
`);
$.each(value, function (ky, val) {
$('#dataTable tbody').append(
`<tr>
<td>
` + ky + `
</td>
<td>
` + val.Item_name + `
</td>
</tr>
`);
});
});
I am facing an inssue whereby all items are being displayed under the first customer while the data is being displayed correctly under the second customer.
You're missing commas after the properties and Jane Doe property's objects aren't enclosed in []. Consider changing your groupedData object as the syntax isn't right.
Edit: Also adjusted the template string and accessing the table with dynamic id as well.
Sample:
let groupedData = {
"John Doe": [{
"Item_id": 1,
"Item_name": "abc"
},
{
"Item_id": 2,
"Item_name": "def"
}
],
"Jane Doe": [{
"Item_id": 3,
"Item_name": "ghi"
},
{
"Item_id": 4,
"Item_name": "jkl"
}
]
};
$.each(groupedData, function(key, value) {
$('.cust_items').append(`
<h4 class="mb-0">${key}</h4>
<table id="dataTable_${key.split(' ').join('_')}">
<thead>
<th>Item No.</th>
<th>Item Name</th>
</thead>
<tbody></tbody>
</table>
`);
$.each(value, function(ky, val) {
$(`#dataTable_${key.split(' ').join('_')} tbody`).append(
`<tr>
<td>
${ky}
</td>
<td>
${val.Item_name}
</td>
</tr>
`);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cust_items">
</div>
I'm a bit late to the party, but here's a fun and practical way to display your data dynamically using the <template> element and vanilla JS.
The in-code comments should make clear how it works.
Note: Be wary of adding the id attribute to elements inside a template (or inside a loop for that matter) cuz duplicate id values are bad.
const data = {
"John Doe" :
[
{ "Item_id" : 1, "Item_name": "abc" },
{ "Item_id" : 2, "Item_name": "def" }
],
"Jane Doe" : [
{ "Item_id" : 3, "Item_name": "ghi" },
{ "Item_id" : 4, "Item_name": "jkl" }
]
};
// Identifies HTML elements and an array of the names
const
container = document.getElementsByClassName("cust_items")[0],
template = document.getElementById("group_template"),
names = Object.keys(data);
// Loops through the names and adds a new copy of the template's contents for each one
for (let name of names){
// Identifies HTML elements (Technically, some are `document fragments`)
const
copyOfTemplate = document.importNode(template.content, true),
header = copyOfTemplate.querySelector(".header"),
tbody = copyOfTemplate.querySelector("tbody");
// Sets the header for the new copy of the template's contents
header.innerHTML = name;
// Loops through the items for this name and makes a new row for each one
for(let item of data[name]){
// Identifies strings and new HTML elements
const
itemId = item["Item_id"],
itemName = item["Item_name"],
row = document.createElement("TR"),
idCell = document.createElement("TD"),
nameCell = document.createElement("TD");
// Sets the item number and item name in their respective cells
idCell.innerHTML = itemId;
nameCell.innerHTML = itemName;
// Adds the cells to the new row
row.appendChild(idCell);
row.appendChild(nameCell);
// Adds the new row to the `tbody` within the new copy of the template's contents
tbody.appendChild(row);
}
// The new copy is ready to go live -- adds it to the page
container.appendChild(copyOfTemplate);
}
.header{ font-size: 1.2em; margin-bottom: 0.3em; }
table{ margin-left: 0.3em; margin-top: 0; border-collapse: collapse; }
th, td{ padding: 0.3em 0.5em; }
<div class="cust_items"></div>
<template id="group_template">
<h4 class="header"></h4>
<table>
<thead>
<th>Item No.</th>
<th>Item Name</th>
</thead>
<tbody></tbody>
</table>
<hr />
</template>
I'm trying to display extra info on child rows without using ajax, the thing is that it works well but I want to display more than one value in a list way.
Something like this
Any suggestions?
I'm using web2py to take the data and fill the table, this is my try:
<script>
var tabla;
$(document).ready(function(){
tabla= $('#tablaGenerica').DataTable( {
} );
function format(value) {
return '<div>Hidden Value: ' + value + '</div>';
}
$('#tablaGenerica').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = tabla.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(tr.data('child-value'))).show();
tr.addClass('shown');
}
});
</script>
<table id="tablaGenerica" class="tablaC table-striped hover cell-border" cellspacing="0" width="100%" >
<thead>
<tr>
<th></th>
<th class="select-filter">Name</th>
<th class="select-filter">Age</th>
<th class="select-filter">Country</th>
<th class="select-filter">Level</th>
</tr>
</thead>
<tbody>
{{for person in formList:}}
<tr data-child-value="{{=person.Person.salary}}">
<td class="details-control"></td>
<td>{{=person.Person.name}}</td>
<td>{{=person.Person.age}}</td>
<td>{{=person.Person.country}}</td>
<td>{{=person.Person.level}}</td>
</tr>
{{pass}}
</tbody>
</table>
I'd suggest to refactor your app slightly, as you don't really need to cook up your HTML server-side, DataTables can handle that for you on the client end.
You may simply prepare the array of objects, where each entry corresponds to the table row and each object property / inner array element - to respective column (or details entry):
[
{id: 1, name: 'Clark Kent', age: 32, country: 'USA', level: 'high'},
{id: 2, name: 'Arthur Curry', age: 31, country: 'USA', level: 'medium'},
{id: 3, name: 'Barry Allen', age: 24, country: 'USA', level: 'low'}
]
In order to link those object properties / inner array items to your table columns, you may use DataTables option columns or columnDefs :
$('#tablaGenerica').DataTable({
...
columns: [
{title: 'ID', data: 'id'},
{title: 'Name', data: 'name'},
...
]
});
After that (and this is the essential part of the answer), in order to show multiple details within your child row, you simply need to modify your format() function, so that it returns HTML markup of the child row with all the necessary details:
const format = data => `
<div>Age: ${data.age}</div>
<div>Country: ${data.country}</div>
<div>Level: ${data.level}</div>
`;
So, complete DEMO of your case might look something, like that:
//specify source data
const dataSrc = [
{id: 1, name: 'Clark Kent', age: 32, country: 'USA', level: 'high'},
{id: 2, name: 'Arthur Curry', age: 31, country: 'USA', level: 'medium'},
{id: 3, name: 'Barry Allen', age: 24, country: 'USA', level: 'low'}
];
//initialize DataTables
const dataTable = $('#tablaGenerica').DataTable({
//specify necessary options to adjust DataTable to your needs
dom: 't',
data: dataSrc,
//specify columns that should be visible initially
columns: [
{title: 'ID', data: 'id'},
{title: 'Name', data: 'name'}
]
});
//declare function that renders child row with hidden details
const format = data => `
<div>Age: ${data.age}</div>
<div>Country: ${data.country}</div>
<div>Level: ${data.level}</div>
`;
//attach event listener to row click
$('#tablaGenerica').on('click', 'tr', function(){
//get clicked row into a variable
const clickedRow = dataTable.row($(this));
//show/hide child row
clickedRow.child.isShown() ? clickedRow.child.hide() : clickedRow.child(format(clickedRow.data())).show();
//toggle 'shown' class
$(this).toggleClass('shown');
});
#tablaGenerica tbody tr.even:hover, #tablaGenerica tbody tr.odd:hover{
cursor: pointer;
background: lightgray;
}
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="tablaGenerica"></table>
</body>
</html>
there is an example for you
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var data = [{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
}];
var table = $('#example').DataTable( {
"data": data,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
td.details-control {
background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;
}
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
I'm trying to fill a HTML table with JSON data. I'm using dynatable plugin.(No specific reason to use this. Just that I bumped on to this & found it's UI to be appealing).
JSON data sample returned by server
[{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}]
Code below -
function jsDataPlot(chartProps) {
// Get the array from the element:
var graphPropsStore = chartProps;
// Loop through the array with the jQuery each function:
$.each(graphPropsStore, function (k, graphPropsStoreProperty) {
// The makeCall function returns a ajaxObject so the object gets put in var promise
var dbResAjx = getResultFromSql(k);
// Now fill the success function in this ajaxObject (could also use .error() or .done() )
dbResAjx.success(function (response) {
console.log(response);
// myRecords = JSON.parse(response.text());
$('#tableIdToFill').dynatable({
dataset: {
records: $.parseJSON(response)
}
});
});
dbResAjx.error(function (response) {
console.log(response);
});
});
}
The problem I have is, tough the JSON response is coming back from the server fine, the table is getting fileld with undefined
Here's the HTML code for the table
<body id="htmlDataTable">
<table id="tableIdToFill" class="display" cellspacing="0" width="98%">
<thead>
<tr>
<th>DATE</th>
<th>TYPE</th>
<th>NAME</th>
</tr>
</thead>
<tfoot>
<tr>
<th>DATE</th>
<th>TYPE</th>
<th>NAME</th>
</tr>
</tfoot>
</table>
</body>
I'm following the article here
Issue is with name of the properties, they need to start with lower-case.
var jsonData = `[
{
"date": "2015-12-15",
"type": "AAA",
"name": "asdasd"
},
{
"date": "2015-12-15",
"type": "BBB",
"name": "dsfsdfsdfsdf"
},
{
"date": "2015-12-15",
"type": "AAA",
"name": "reterter"
},
{
"date": "2015-12-15",
"type": "CCC",
"name": "ertertertert"
}
]`;
//console.log(jsonData);
var response = JSON.parse(jsonData);
console.log(response);
$('#tableIdToFill').dynatable({
dataset: {
records: response
}
});
See this jsFiddle