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
Related
This is in the variable "test":
{"data":[{"HistChar_ID":"4","Vorname":"Garnier","Nachname":"de
Naplouse"},{"HistChar_ID":"2","Vorname":"Robert","Nachname":"de
Sable"},{"HistChar_ID":"7","Vorname":"Ibn","Nachname":"Dschubair"},{"HistChar_ID":"6","Vorname":"Baha
ad-Din","Nachname":"ibn
Schaddad"},{"HistChar_ID":"1","Vorname":"Richard","Nachname":"L\u00f6wenherz"},{"HistChar_ID":"5","Vorname":"Wilhelm","Nachname":"von
Montferrat"}]}
HTML:
<table id="example" class="display" style="width:100%">
<thead class="thead1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</thead>
<tfoot class="tfoot1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</tfoot>
</table>
An the following Code Wont fill the Datatable.
$('#example').DataTable({
data: test,
columns: [
{ data: 'HistChar_ID' },
{ data: 'Vorname' },
{ data: 'Nachname' },
]
it throws an Error like this:
DataTables warning: table id=example - Requested unknown parameter
'HistChar_ID' for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4
I tried so much. But if i take whats inside of "test" and put it into a php and use ajax it works just fine with this.
$('#example').DataTable({
ajax: 'RESOURCES/PHP/Searchfield.php',
columns: [
{ data: 'HistChar_ID' },
{ data: 'Vorname' },
{ data: 'Nachname' },
]
PHP/Searchfield
include 'connection.php';
$searchstuff = $_GET['Searchfield'];
$sql = "select * FROM historischercharacter WHERE Vorname LIKE '%$searchstuff%' OR Nachname LIKE '%$searchstuff%' ORDER BY Nachname" ;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode(array('data'=>$emparray));
mysqli_close($conn);
Can someone explain me why? Is it impossible to fill the Datatable with a variable?? I just dont get it...
If you look at the examples in the documentation, the hard-coded array being passed into the table doesn't have the outer data property, it's just an array by itself - see https://datatables.net/examples/data_sources/js_array.html . You can see the same thing here as well: https://datatables.net/reference/option/data
The requirements when defining an AJAX data source are different. As per the example at https://datatables.net/reference/option/ajax by default you must supply an object with a "data" property as per the structure you've shown us in your question.
So it's simply that the requirements for each type of data source are different. Always read the documentation!
Demo of how to set the data source using a variable, with your variable. Note the absence of the "data" property...instead "test" is just a plain array:
var test = [{
"HistChar_ID": "4",
"Vorname": "Garnier",
"Nachname": "de Naplouse"
}, {
"HistChar_ID": "2",
"Vorname": "Robert",
"Nachname": "de Sable"
}, {
"HistChar_ID": "7",
"Vorname": "Ibn",
"Nachname": "Dschubair"
}, {
"HistChar_ID": "6",
"Vorname": "Baha ad-Din",
"Nachname": "ibn Schaddad"
}, {
"HistChar_ID": "1",
"Vorname": "Richard",
"Nachname": "L\u00f6wenherz"
}, {
"HistChar_ID": "5",
"Vorname": "Wilhelm",
"Nachname": "von Montferrat"
}];
$('#example').DataTable({
data: test,
columns: [{
data: 'HistChar_ID'
},
{
data: 'Vorname'
},
{
data: 'Nachname'
},
]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead class="thead1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</thead>
<tfoot class="tfoot1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</tfoot>
</table>
Here is an example using a JavaScript variable which does not require you to change the data you show in your question:
var test = { "data": [ { ... }, { ... }, ... ] };
In the above structure, each element in the array [ ... ] contains the data for one table row.
In this case, the DataTable uses the data option to specify where that array can be found:
data: test.data
Here is the runnable demo:
var test = {
"data": [{
"HistChar_ID": "4",
"Vorname": "Garnier",
"Nachname": "de Naplouse"
}, {
"HistChar_ID": "2",
"Vorname": "Robert",
"Nachname": "de Sable"
}, {
"HistChar_ID": "7",
"Vorname": "Ibn",
"Nachname": "Dschubair"
}, {
"HistChar_ID": "6",
"Vorname": "Baha ad-Din",
"Nachname": "ibn Schaddad"
}, {
"HistChar_ID": "1",
"Vorname": "Richard",
"Nachname": "L\u00f6wenherz"
}, {
"HistChar_ID": "5",
"Vorname": "Wilhelm",
"Nachname": "von Montferrat"
}]
};
$(document).ready(function() {
$('#example').DataTable({
data: test.data,
columns: [
{ data: 'HistChar_ID' },
{ data: 'Vorname' },
{ data: 'Nachname' },
]
} );
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%">
<thead class="thead1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</thead>
<tfoot class="tfoot1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
JavaScript Data Sources
In the above example, the data is sourced from a JavaScript variable - so at the very least you always need to tell DataTables what the name of the JS variable is, using the data option.
And, you may also need to tell DataTables where the array of row data can be found in that variable. This is what we needed to do in the above example.
If the JavaScript variable had been structured like this (an array, not an object containing an array)...
var test = [ { ... }, { ... }, ... ];
...then in that case, we only need to use data: test in the DataTable.
Ajax Data Source
For Ajax-sourced data, things are slightly different. There is no JavaScript variable - there is only a JSON response.
By default, if that JSON response has the following structure (an array of objects called "data" - or an array of arrays)...
{ "data": [ { ... }, { ... }, ... ] }
...then you do not need to provide any additional instructions for DataTables to locate the array. It uses "data" as the default value.
Otherwise if you have a different JSON structure, you need to use the Ajax dataSrc option to specify where the array is in the JSON response.
For the above example, if you do not provide the dataSrc option, that is the same as providing the following:
ajax: {
url: "your URL here",
dataSrc: "data" // this is the default value - so you do not need to provide it
}
This is why your Ajax version "just works" when you only provide the URL:
ajax: 'RESOURCES/PHP/Searchfield.php'
DataTables is using the default value of data to find the array it needs.
And this is why it doesn't work when you use a JavaScript variable called test with data: test.
So, for JavaScript-sourced data, there is no default value. You always have to provide the JavaScript variable name - and maybe additional info for the location of the array in the varaible.
But for Ajax-sourced data, there is a default value (data) - and I believe this is only provided for backwards compatibility with older versions of DataTables.
I am using table for showing the datas and for data I am using Api.
Api data looks like::
{
"data": [
{
"id": "1",
"name": "name1",
"label": "label1"
},
{
"id": "2",
"name": "name2",
"label": "label2"
},
{
"id": "3",
"name": "name3",
"label": "label3"
}
]
}
html code
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Label</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of sample;">
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.label}}</td>
<tr>
<tbody>
<table>
I need the 10 table rows statically(fixed). The table data is from API. For exanple ,Api contains 2 data... Then UI table should be with 2 rows of data and balance with emply rows... but there should display 10 rows(Mandatory)
which means in UI i want 10 rows with data from Api and balance should be empty.
You can fix in view layer, ts layer or even backend API layer (Not really recommended).
In view layer if you loop over your data, you can calculate if your data's size goes over arbitrary threshold and if not loop again to display as many empty rows as possible.
In ts layer, when you receive data from api you can modify variable you pass to your view by adding to an array as many empty items as you need.
What's important if you use null, then you have to check for it with for example elvis operator.
I would advise agains adding to an array an object with all properties set to null, because then these are not so easily distinguishable from valid data from API and you can for instance make some rows interactive, even though they should not be.
const dataFromApi = [{ "id": "1", "name": "name1" }, { "id": "2", "name": "name2" }]
const minRowsNumber = 10;
const diff = minRowsNumber - dataFromApi.length;
const viewTableData = diff > 0 ? dataFromApi.concat(new Array(diff).fill(null)) : dataFromApi;
console.log(viewTableData)
Example in AngularJs (No Angular in SO Snippets, but it is the same principle)
angular.module('example', [])
.controller('ExampleController', function ExampleController() {
const dataFromApi = [{ "id": "1", "name": "name1" }, { "id": "2", "name": "name2" }]
const minRowsNumber = 10;
const diff = minRowsNumber - dataFromApi.length;
this.viewTableData = diff > 0 ? dataFromApi.concat(new Array(diff).fill(null)) : dataFromApi;
});
table {
border-collapse: collapse;
}
td, th {
border: 1px solid black
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="example" ng-controller="ExampleController as example">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in example.viewTableData track by $index">
<td>{{row ? row.id : ' '}}</td>
<td>{{row ? row.name : ' '}}</td>
</tr>
</tbody>
</table>
</div>
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>
I was able to get result from MVC controller using ajax, it returns me json data. Now i need to put it to html table in view, how can i do it?
function getClassificators(){
$.ajax({
url:"/Employee/GetClassificationLevels",
type:"GET",
success: function(result){
if(Array.isArray(result) && result.length > 0){
var eachRes = result.map(function(classificator, i){
return {
levels: classificator.Level,
name: classificator.Name,
score: classificator.Score,
sublevel_info : classificator.EmpEvaluation_SubLevelView.map(function(sublevelinfo, i){
return {sublevel_name: sublevelinfo.Name};
})
};
});
}
},
error: function(err){
console.log(err);
}
});
}
console shows:
[{
{levels:0, name: "level4", score:3, sublevel_info:{sublevel_name:"sublevel4"}}
}]
Expected output is html table.
Take a look at DataTables.js.
It has ajax support out of the box, and it's raelly easy to use.
Here an example
var dtTickets = $("#dtTickets");
datatable = $(dtTickets).DataTable(
{
"order": [[0, "desc"]],
"createdRow": function (row, data, index) {
$(row).data("userId", #id);
$(row).data("ticketId", data.id);
$(row).addClass("selectable");
},
"ajax": {
"url": "#Url.Action("TicketsAjax", "User")",
"type": "POST",
"data": function (d) {
// Set here variables for you AJAX POST message.
d.id = #id;
d.companyId = #summary.CompanyId;
d.filtersJson = searchParms.filtersToJson();
console.log(d);
},
"dataSrc": function (response) {
// You can process the response here if needed.
return response;
}
},
"columns": [
{
"className": "text-right"
"data": "id"
},
{ "data": "createDate" },
{ "data": "createUserName" },
{ "data": "title" },
{ "data": "status" },
{ "data": "actionDate" },
],
}
);
Make sure that your table is structured like this
<table>
<thead>
<tr>
<th>test</th>
<th>somecolumn</th>
</tr>
</thead>
-> I have a answer but in pure JS, not in jQuery – Mister Jojo
-> can u share it please? – Valery
it looks like that
suposed HTML:
<table id="my-table">
<thead>
<td>Level</td><td>Name</td><td>Score</td>
</thead>
<tbody></tbody>
</table>
JS:
const Url = '/Employee/GetClassificationLevels'
, myTableBody = document.querySelector('#my-table tbody')
fetch(Url)
.then(resp=> resp.json())
.then(data=>{
// ...
data.forEach(classificator=>{
let eRow = myTableBody.insertRow(-1)
, nCol = 0
eRow.insertCell(nCol++).textContent = classificator.Level
eRow.insertCell(nCol++).textContent = classificator.Name
eRow.insertCell(nCol++).textContent = classificator.Score
//...
})
})
I am working on a angular project. i have a scenario where i need to list some details in a page of the application.I have a service call in the page which returns the following json structure. i want to loop through this json structure to list few of the data in the response.
[
{
"ProductDetails": [
{
"ProductType": "Application1",
"Name": "Product1",
"New": false,
"Category": "product",
"Country": "India",
"description": "Description for Product1",
"Favourite": false,
"settings": {
"WebsiteFlag": true,
"SmsFlag": false,
"EmailFlag": true
}
}
]
},
{
"ProductDetails": [
{
"ProductType": "Application2",
"Name": "Product2",
"New": true,
"Category": "product",
"Country": "India",
"description": "Description for Product2",
"Favourite": true,
"settings": {
"WebsiteFlag": false,
"SmsFlag": false,
"EmailFlag": true
}
}
]
}
]
JS
$ctrl.getSettings = function () {
var url = "http://localhost:3000/json/settings-updated.json";
rsicontext.getData(url).then(function (response) {
$ctrl.Settings = response.data;
});
}
HTML
<tbody>
<tr data-ng-repeat="app in $ctrl.Settings" class="content-box">
<td data-ng-bind="app.ProductDetails.ProductType"></td>
<td data-ng-bind="app.ProductDetails.Name"></td>
<td><ng-checkbox data-checked="app.SmsFlag" rounded="true"></ng-checkbox></td>
<td><ng-checkbox data-checked="app.EmailFlag" rounded="true"></ng-checkbox></td>
</tr>
</tbody>
I am trying to list the Product Type, Name, EmailFlag and SmsFlag. How can i loop through the json structure to list the data.
Simply go over the response and build a new array from the fields you need. Like so:
var d = [];
for( vari=0;i< response.data.ProductDetails.length; ++i) {
var curr= {
ProductType: response.data.ProductDetails[i].ProductType,
Name: response.data.ProductDetails[i].Name
}
d.push(curr);
}
$ctrl.Settings = d;
To manipulate object or array I always use a library called underscore.js
This can help you to do what you want.
var plucked=_.pluck($ctrl.Settings, 'ProductDetails');
This function will return an array of object. Then you can loop it.
https://jsfiddle.net/wz2njukj/
You can achieve this throw ng-repeat
<div ng-repeat="d in data[0].ProductDetails[0]">
{{ d.SmsFlag }} {{ d.WebsiteFlag}} {{d.EmailFlag}}
</div>
Look this and get data as you want.
PlunkerHere
ProductDetails contains an array, so you would have to nest ngRepeats
<span data-ng-repeat="detail in app.ProductDetails">
If you know that ProductDetails will only have one element it would be best to change the structure that is being generated if you can. If not you can access it in markup
<tbody>
<tr data-ng-repeat="app in $ctrl.Settings" class="content-box">
<td data-ng-bind="app.ProductDetails[0].ProductType"></td>
<td data-ng-bind="app.ProductDetails[0].Name"></td>
<td><ng-checkbox data-checked="app.ProductDetails[0].settings.SmsFlag" rounded="true"></ng-checkbox></td>
<td><ng-checkbox data-checked="app.ProductDetails[0].settings.EmailFlag" rounded="true"></ng-checkbox></td>
</tr>
</tbody>
Or you can massage the data in your controller before passing it off to the view.
$ctrl.Settings = response.data.map(products=>products.ProductDetails[0])