DataTable with JSON data - javascript

I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.
function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var JSONObject = JSON.parse(request.responseText);
createTable(JSONObject);
} else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}
Requesting the JSON file via a XMLHttpRequest() request.
short sample of the JSON object:
{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
"report-metadata": {
"timestamp": 1528235303.721987,
"from-ip": "0.0.0.0"
},
//and so on...
Currently only trying to show the meta part in a DataTable table:
function createTable(jsonData){
$(document).ready(function(){
$('#table').dataTable({
data: jsonData,
columns: [
{ data: 'meta.type' },
{ data: 'meta.version' }
]
});
});
}
index.html part:
<table id="table" class="display" style="width:100%"></table>
Only getting a No data available in table when running, and I am obviously missing something.

The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.
var jsonData = [
{ "meta": { "version": 1, "type": "test" } }
];
$('#table').DataTable({
"data": jsonData,
"columns": [
{ "data": "meta.type" },
{ "data": "meta.version" }
]
});
https://datatables.net/reference/option/data
Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax

Related

fill datatable from php and javascript

Thanks everyone solved by using JSON.parse(xhttp.responseText);
hello i trying to fill up datatable from a php file the data is generator from database then use echo json
and handle the response from javascript here is the php file
<?php
global $wpdb;
$db_list = $wpdb->get_results("SELECT dbtest.FName, dbtest.SName FROM dbtest");
echo json_encode($db_list);
exit;
?>
and here is how i trying to handle the data in javascript
<script>
const xhttp = new XMLHttpRequest()
xhttp.open("GET", "datatabletest.php")
xhttp.send()
http.onload = function() {
var response = xhttp.responseText;
console.log(response);
//from here problem start
$('#example').DataTable({
"data": response,
"columns": [
{ "data": "FName" },
{ "data": "SName" }
]
});
}
</script>
but it alert error DataTables warning: table id=example - Requested unknown parameter 'FName' for row 0, column 0.
it looks like the data from response is null but in console it showing as
[{"FName":"test","SName":"test2"}]
so i have tried to copy this line from console and add it into a var like
var jsdata = [{"FName":"test","SName":"test2"}];
//then use
$('#example').DataTable({
"data": jsdata,
"columns": [
{ "data": "FName" },
{ "data": "SName" }
]
});
}
and that worked so why it not working from the response what is missing to make it work like that

Rendering local JSON data into a Tabulator Table

I'm attempting to implement local JSON data into a Tabulator table. I specifically want to display the obj.File.Name JSON element.
I can render the data into a regular table, but when I incorporate Tabulator the data doesn't render at all. I think the problem lies with the Tabulator Section that's listed in the JS Snippet, but I'm not 100% sure. I'm interested in using Tabulator because of the features it offers.
Unless I misread it, the Tabulator docs on loading data seems to be less focused on local files and more on external URLs, which is why I've come to ask about it here.
I've included a JS Fiddle that shows the HTML and the JS.
JS snippet:
import $ from 'jquery';
import JSONfile from '../../../public/JSONfile.json';
import { basename } from 'path';
var Tabulator = require('tabulator-tables');
var categories = '';
var tableRes = '';
export default class {
constructor() {
this.loadData();
this.loadTableData();
}
loadTableData() {
let tableRes = JSONfile.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
///// Tabulator Section /////
let tableData = tableRes;
let table = new Tabulator("#km-table-id", {
data:tableData,
columns:[
{title:"", field:" "},
{title:"All Templates", field:"Name"},
{title:"My Favorites", field:"faves"}
],
pagination:"local",
paginationSize:100,
placeholder:"No data available"
});
table.setData(tableData);
} // ------------------ loadTableData
} // ------------- export default class
JSON snippet:
{
"d": {
"results": [
{
"__metadata": {
...
},
"File": {
"__metadata": {
...
},
"Name": "Guide to Product IDs.docx"
},
"FileLeafRef": "Guide to Product IDs.docx",
"ResourceType": {
...
},
"results": [
{
...
}
]
},
"EncodedAbsUrl": [redacted]
},
...
...
The issue you are having is because the data is not in the format that Tabulator is expecting.
Tabulator requires an array of row data objects, based on your column definitions it is looking for this:
[
{Name:"steve", faves:"this, that, the other"},
{Name:"bob", faves:"this, that, the other"},
]
Loading local data into the table is covered in the Documentation

mLAB Insert document into a collection API

Below is the code snippet I am using :
request.post('https://api.mlab.com/api/1/databases/db/collections/coll?apiKey=APIKEY',
{ json: {result} },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("----->"+body);
}
else
console.log("-----XXXXX>"+error);
});
Now result is a javascript var which is a string and has a proper json stored in it in the below form:
{
"key1":"value1",
"key2" : "value2",
....
"key100":"value3"
}
So basically in collection coll I need to insert above json as a document.
Output of above code is below :
{
"_id": {
"$oid": "5a71c84ac2ef165da041df86"
},
"result": "{\"key1\":\"val1\",\"key2\":\"val2\"}"
}
The above is the Json document that I am getting after executing the piece of NodeJs code shown at top and also I have shown the contents of string result.
I just need at the a json document like below:
{
"key1":"val1",
.....
"key100":"val100"
}

How to create complex javascript object for JSON API

Below is the structure of JSON which I use to query an API
"order_items": [
{
"menu_item_id": "VD1PIEBIIG",
"menu_item_name": "Create Your Own",
"modifiers": [
{
"modifier_id": "6HEK9TXSBQ",
"modifier_name": "Shrimp"
}
],
"quantity": "1",
"total": 15.99,
"variant_id": "TXDOR7S83E",
"variant_name": "X-Lg 18\""
}
]
Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. But I am not able to create the Javascript object. Can anyone help with this?
Like i want to have the following structure
obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";
and so on.
var jsonToSend = { "order_items": [ ] };
// then for each order item
var orderItem = { "menu_item_id": <whatever>,
"menu_item_name": <whatever>,
"quantity": <whatever>,
"total": <whatever>,
"variant_id": <whatever>,
"variant_name": <whatever>,
"modifiers": []
};
// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);
jsonToSend.order_items.push(orderItem);
JSON.stringify(jsonToSend);
Well there are a couple of ways to do this.
Manually create the Json object to send from the HTML elements:
$.ajax({
type: "POST",
url: "some.php",
data: new {"order_items": [
{
"total": $('total').Val(),
"variant_id": $('variant_id').Val(),
"variant_name": $('variant_name').Val()
}
]})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
You could use a great framework like KnockoutJs, this will keep your JSON object up to date with your form, so that you don't have to do it manually. When you are ready you just submit your original json back to the server.
See this basic example on JsFiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};
this.resetClicks = function() {
this.numberOfClicks(0);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right.
See SerializeArray
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});

Function doesn't display data from JSON

In my webapp I have a page where I use getJSON to get data from server. Firebug shows that it get's JSON from server just the way it is supposed to, but no data is shown. What could be the problem? Here is what my code looks like:
$('#detailsPage').live('pageshow', function(event) {
var id = getUrlVars()["id"];
$.getJSON(serviceURL + 'getemployee.php?id='+id+'&callback=?', displayEmployee);
});
function displayEmployee(data) {
var employee = data.item;
$('#employeePic').attr('src', 'pics/' + employee.PIC);
$('#fullName').text(employee.NAME);
$('#employeeTitle').text(employee.TITLE);
$('#lisatieto').text(employee.INFO);
if (employee.puhelin_nro) {
$('#actionList').append('<li><h3>Soita puhelimeen</h3></li>');
$('#actionList').append('<li><h3>SMS</h3></li>');
}
$('#actionList').listview('refresh');
}
Console shows
employee is undefined
[Break On This Error]
$('#employeePic').attr('src', 'pics/' + employee.PIC);
This is the JSON response:
jQuery164008509381752724021_1336981793995({
"key": [
{
"PIC": "Tuntematon",
"NAME": "0",
"TITLE": "0",
"INFO": "0"
}
]
})
You need to use this
var employee = data.key[0];

Categories

Resources