Iterate through the AJAX url in the render from Datatables - javascript

The thing is that i am trying to fill a datatable like this
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data.name+'\'s row' );
$.ajax({
url: data.url,
dataType: 'json',
success: function(json){
console.log(json)
tableDos.rows.add([json]).draw();
}
});
} );
What this does is that when someone selects a row from another datatable that its already filled, it is going to extract the URL of the selected JSON from the row (The JSON comes from SWAPI.CO API) and passed it through to fill another datatable like this.
var tableDos = $('#exampleDos').DataTable({
"columns": [{
"title": "Films",
"data": "films",
render: function (data, type, row, meta) {
var currentCell = $("#exampleDos").DataTable().cells({"row":meta.row, "column":meta.col}).nodes(0);
// $.each(data, function (i, item){
$.ajax({
url: data[0],
success: function(json){
console.log(json)
$(currentCell).text(json.title);
}
});
// })
return null;
}
},
{
"title": "Vehicles",
"data": "vehicles"
},
{
"title": "Starships",
"data": "starships"
}
]
});
The tricky part comes here, what this table is receiving is coming from this JSON
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
So my table as you can see is receiving films, vehicles and starships in the form of an array and URL so i have to do another AJAX call as you can see in the table from for example "films" so i in the AJAX url i have to iterate through the films ARRAY but it automatically iterates without using loops or each and i cant make it work. It seems confusing but check it out for yourselves.
https://jsfiddle.net/um8tmgq2/2/

Related

Query datatable from rest api without pre-defining the table in html

I would like to query a JSON via post request from a rest API:
http://localhost/post1
param1='1'
that returns the following:
{
"json_table": [
{
"date": 123,
"test": "hello2"
},
{
"date": 19,
"test": "hello"
},
}
and it should then be automatcially populated into a jquery datatable, a little bit how it is described here:
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
What I don't understand is:
How can I tell it to make a post request with a parameter
How can I create the table without having to predefine it in HTML, so that it's completely agnostic what is returned from the JSON and just displays the table accordingly, whatever is within the 'json_table' record (which is generated from a pandas data frame df.to_json(orient='records')?
How can I make it refresh (query again) every 15 seconds and update the table?
Any suggestions are appreciated.
To make the post request with parameters , U can do is:
$.ajax({
type: 'POST',
dataType: "json", #define the response type as Json
url: url,
data: data, # make a post request with a parameter you want
success: success
});
U can create table with json data like this :
<script type="text/javascript">
var myContacts = [{ "name": "Parvez Ansari", "email": "ansariparvez#gmai.com", "mobile":"9998979695" },
{ "name": "Tayyeb Shaikh", "email": "tshaikh1981#gmai.com", "mobile":"9091929394" },
{ "name": "Ashfaque Shaikh", "email": "ashly786#gmai.com",
"mobile":"8081828384" }
];
function generateDynamicTable(){
var noOfContacts = myContacts.length;
if(noOfContacts>0){
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');
// retrieve column header ('Name', 'Email', and 'Mobile')
var col = []; // define an empty array
for (var i = 0; i < noOfContacts; i++) {
for (var key in myContacts[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.createElement("thead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.createElement("tr");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
hRow.appendChild(th);
}
tHead.appendChild(hRow);
table.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < noOfContacts; i++) {
var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
td.innerHTML = myContacts[i][col[j]];
bRow.appendChild(td);
}
tBody.appendChild(bRow)
}
table.appendChild(tBody);
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("myContacts");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
}
</script>
U can refer this code for refreshing in every 15 mins :
Check this Ans
Creating a dynamic DataTable from arbitrary JSON is certainly possible - but it can get complicated depending on how many of the features of DataTables you are trying to use.
Also, if you have control over the JSON being sent from the server, you can make things easier for yourself. I will assume you do have such control for what follows.
Static Example
Assume we start with this simple static example:
The server sends this JSON data:
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architext",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421",
"toggle": "off"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "1278",
"toggle": "on"
}
]
}
And we have a simple DataTables definition like this:
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%"></table>
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": {
"url": "http://localhost:7000/employees",
"dataSrc": "data",
"type": "GET",
},
"columns": [
{ "data": "name",
"title": "Name" },
{ "data": "position",
"title": "Position" },
{ "data": "office",
"title": "Office" },
{ "data": "extn",
"title": "Extn." },
{ "data": "start_date",
"title": "Start Date" },
{ "data": "salary",
"title": "Salary" },
]
} );
} );
</script>
</body>
Enhancing the JSON
To make things easier for ourselves, we can enhance the JSON being sent from the server, to contain metadata about the columns in the data records:
{
"response": [
{
"columns": [
{
"data": "name",
"title": "Name"
},
{
"data": "position",
"title": "Position"
},
{
"data": "office",
"title": "Office"
},
{
"data": "extn",
"title": "Extn."
},
{
"data": "start_date",
"title": "Start Date"
},
{
"data": "salary",
"title": "Salary"
}
]
},
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architext",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421",
"toggle": "off"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "1278",
"toggle": "on"
}
]
}
]
}
This new columns section in the JSON is basically the same information as was hard-coded into the first DataTables definition.
We can read that into a variable, when we receive the JSON from the server, and then use this variable in our DataTables configuration.
And we can do the same thing for the data records also:
var tableData = [];
var tableColumns = [];
...
$('#example').DataTable( {
"data": tableData,
"columns": tableColumns
} );
For more flexibility, the ajax request can be separated out from DataTables:
<script type="text/javascript">
var tableData = [];
var tableColumns = [];
function ajax1() {
return $.ajax({
url: "http://localhost:7000/employees",
success : handleData,
type: "POST",
data: { "foo": "bar" }
});
}
function handleData(data) {
tableData = data.response[1].data;
//console.log(JSON.stringify(tableData));
tableColumns = data.response[0].columns;
}
$(document).ready(function() {
$.when(ajax1()).done(function(a1){
$('#example').DataTable( {
"data": tableData,
"columns": tableColumns
} );
});
} );
</script>
The easiest way to assemble what you need is (I think) to write the hard-coded version of your data table - and then to start replacing pieces with dynamically created variables.
POST with parameters
The above ajax example includes these lines:
type: "POST", // request type (watch out for CORS!)
data: { "foo": "bar" } // request body (form parameters)
This means the ajax request will be a POST and will contain a request body in this case containing foo=bar. You can, of course put whatever you need in there. It's standard form data. The server would read this data in whatever standard way it uses (e.g. request context form parameters).
Auto-Refresh
I haven't done this myself, but there are solutions documented using setInterval - something like this:
setInterval( function () {
console.log("reloading");
}, 2000 ); // milliseconds
Final note - just to reiterate - this is not going to be able to handle whatever JSON you throw at it. And if you have no control over the JSON structures, then there may well be too many differences from one payload to the next.
But if you control the JSON and if you want to define more features (e.g. default sorting, hidden columns) then you can start adding those to the JSON as additional metadata items.
Hope that helps or at least gives you some pointers.
By the way, there should generally be no need to use code which manipulates the DOM (e.g. building strings of HTML, or manipulating tags). That is counter to how DataTables is designed to work. You should instead be working with the DataTables object itself, wherever possible.

how to export complex json to excel with alasql

I have a json like this (there might be some syntax errors, I did extract and rewrite some private data)
"todo-items": [{
"id": 3511710,
"company-name": "company1",
"author" : "Jon Doe",
"tags": [{
"id": 10101,
"name": "2.Marketing Sales",
"color": "#f78234"
}],
"creation-date": 20160101
}, {
"id": 3511474,
"company-name": "company1",
"author" : "Jon Don",
"tags": [{
"id": 10101,
"name": "2.Marketing Sales",
"color": "#f78234"
}, {
"id": 10103,
"name": "4.Automotive",
"color": "#9b7cdb"
}],
"creation-date": 20160101
}, {
"id": 3511478,
"company-name": "company1",
"author" : "Peter Jon Doe",
"tags": [{
"id": 10101,
"name": "2.Marketing Sales",
"color": "#f78234"
}, {
"id": 9706,
"name": "3.sales",
"color": "#37ced0"
}, {
"id": 9562,
"name": "3.IT",
"color": "#37ced0"
}],
"creation-date": 20160101
}]
and I use alasql with xlsx.core libraries to export this to excel file.
For first I remove STATUS from original json (provided by teamwork API) and then I change JSON to javascript array
$.ajax({
type: "GET",
url: requrl,
headers: {"Authorization": "BASIC " + window.btoa(key + ":xxx")},
success: function(data) {
delete data.STATUS;
//alert(data);
//console.log(data);
var arr = $.map(data, function(el) { return el });
//console.log(arr);
alasql("SELECT * INTO XLSX('test.xlsx',{headers:true}) FROM ? ",[arr]);
},
error: function(response) {
alert(response);
}
});
this works nice and I can my json extract as excel file
but I have issues with tags objects in this json..when I change it to array and then save it in excel, all columns are ok except tags, where I see just [object][object]
Could you help me how to get these tags also into correct array? The best would be one tag = one column in excel
edit:
this is desired output - max # of tags in JSON will define number of columns tags (doesnt matter if it is tags tags tags or tags tags2 tags3)

json, ajax with a hash

i wondering if there any solution to get data from json in this format:
{ "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">":[{"id":68,
"name":"johnny",
"description":"Hello my first Description",
"created_by_user_id":16530,
"created_at":"2016-01-28T13:17:51.827Z",
"updated_at":"2016-01-29T10:40:40.011Z",
"receiver_group_id":3,"dynamic_fields":{
"files":[
{
"id":2,
"date":"2016-01-29T10:40:35.720Z",
"path":"http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public":null
}
]} }]}
like i want to have a name and description. but if i call in ajax like this:
$(function(){
$.ajax({
url: './dataModel.json',
dataType: 'json',
method: 'GET',
success: function(data){
console.log(data[0].name);// error name is not defined
console.log(data.name); // undefined
}
});
})
may be you guys have some idea how can i get the name and description? thank you so much for any kind of suggestion and idea.
best regard,
ape
Try this:
var input = {
"#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">": [{
"id": 68,
"name": "johnny",
"description": "Hello my first Description",
"created_by_user_id": 16530,
"created_at": "2016-01-28T13:17:51.827Z",
"updated_at": "2016-01-29T10:40:40.011Z",
"receiver_group_id": 3,
"dynamic_fields": {
"files": [{
"id": 2,
"date": "2016-01-29T10:40:35.720Z",
"path": "http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public": null
}]
}
}]
};
var output = Object.keys(input).map(function(key) {
return input[key];
})[0];
alert(output[0].name);

How to parse JSON received from Datatables ajax call?

I can successfully fill my datatable with ajax call, but then I don't know how to parse JSON that is received by datatable with this ajax call.
Here is my JavaScript code, that makes ajax call to the server and fills my datatable correctly:
$('#transactions').DataTable({
"processing": true,
"ajax": {
"url": "/transactions
},
"columns": [
{ "data": "car"},
{ "data": "card_number"},
{ "data": "invoice"},
{ "data": "status"}
]
});
This is the JSON object returned from the server:
{
"data": [
{
"car": 190,
"card_number": "6395637",
"invoice": 200,
"status": "success"
},
{
"car": 191,
"card_number": "9473650",
"invoice": 180,
"status": "success"
}
],
"balance": 7300
}
As you can see, the data parameter of the returned JSON object is used by the datatables function to fill by datatables, and now I want to parse the balance parameter, but I can't. How can i achieve this?
Something like this:
$('#transactions').dataTable({
"ajax" : {
"url" : "/transactions",
"dataSrc" : function (json) {
// manipulate your data (json)
...
// return the data that DataTables is to use to draw the table
return json.data;
}
}
});
Docs: https://datatables.net/reference/option/ajax.dataSrc
Don't use the url feature of DataTable, make the Ajax call yourself
$.getJSON('/transactions', function(response) {
$('#transactions').dataTable({
processing: true,
data: response.data,
columns: [
{ data: "car"},
{ data: "card_number"},
{ data: "invoice"},
{ data: "status"}
]
});
window.someGlobalOrWhatever = response.balance
});
Since DataTables 1.10, you may use the ajax.json() function: https://datatables.net/reference/api/ajax.json()
I have implemented it in the example code below.
$( document ).ready(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var table = $('#location-table').DataTable({
destroy: true,
ajax: "/locations.json",
columns: [
{ "data": "code" },
{ "data": "status" },
{ "data": "name" },
{ "data": "region" },
{ "data": "address" },
{ "data": "city" },
{ "data": "state" },
{ "data": "zip" },
{ "data": "phone_number" },
]
})
table.on( 'xhr', function () {
var json = table.ajax.json();
$('#totals').text(json.totals)
});
})
});
NOTE for this to work you must initialize the datatable with $('#location-table').DataTable() and not $('#location-table').dataTable (the difference being the capitalized D)

Understanding JSON and displaying

I have the following ajax request...
Ajax
function initUpdate()
{
var id = $(this).attr('id').split('_')[1];
//grab id from link update_xxxx
//get all gallery information
$.ajax(
{
type: 'POST',
url: 'ajax/update',
data: {"id": id},
dataType: 'json',
success: function(json)
{
//query was successful now populate form
$("input[name='galleryName']").val(/*what goes here?*/);
}
});
}
That returns the following data
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
}
]
}
How would I access "name" to insert in the val()?
Thanks!
What have you tried? I would think you could get to it via:
json.selected_gallery[0].name
selected_gallery is a JavaScript array, so you would access the first item in the collection using [0] in order access the first item's properties.
UPDATE
You could access other items in the array if they existed:
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
},
{
"id": "5005",
"name": "blah",
"clientRef": "405",
"clientName": "Dave "
},
{
"id": "6006",
"name": "boo",
"clientRef": "605",
"clientName": "Doug"
}
]
}
To get the second item in the array, you'd reference it as:
json.selected_gallery[1].name (or id or clientRef or ...). You can get to the third item via json.selected_gallery[2].name.
Hope this helps.

Categories