Get data in json using javascript and datatables - javascript

I have a javascript as below, which can fetch the data from backed in json format. But How can i pass it to another function , i.e datatables to populate it
<script>
var returndata;
$.getJSON("/api/dashboard_data/", success);
function success(data) {
returndata = data;
window.alert(returndata);
return returndata;
// do something with data, which is an object
}
$(document).ready(function() {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
} );
} );
</script>
In above code in window.alert(returndata), i get the json data which has been returned from backed.
But the same variable "returndata" when i use it in function ready it is empty. How can i get it in ready function.

You are calling two asynchronous functions here. $.getJSON() and $(document).ready(). It looks that ready() is faster than getJSON() which means returndata is empty when you try to fill your data table.
Try this to make sure you have always the correct order:
<script>
$(document).ready(function() {
$.getJSON("/api/dashboard_data/", function(returndata) {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
});
});
});
</script>

Firstly, which jQuery plugin are you using for DataTables? Is it this one? The first thing I would do would be to put everything inside the $document.ready() as the documentation demonstrates. This ensures that all your code executes after the DOM is ready. Let me know what happens after that.
Also this part of the documentation could help if you are using the DataTables API. It could be as simple as a misspelling depending on what you're trying to do as quoted from the docs here:
The result from each is an instance of the DataTables API object which has the tables found by the selector in its context. It is important to note the difference between $( selector ).DataTable() and $( selector ).dataTable(). The former returns a DataTables API instance, while the latter returns a jQuery object.

I know this is not a good solution, just a hack. You can use window.setInterval or window.setTimeout function to check for data and execute the required function. Don't forget to clear the interval.

Follow the Datatables documentation: https://datatables.net/examples/server_side/simple.html
You'll have to do something like this:
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": _getData(),
"columns": [
{title: "Action"},
{title: "Input"},
{title: "State"},
{title: "Completed"},
{title: "Project"}
]
});
function _getData(data, callback) {
$.getJSON("/api/dashboard_data/", success);
function success(data) {
// you'll probably want to get recordsTotal & recordsFiltered from your server
callback({
recordsTotal: 57,
recordsFiltered: 57,
data: data
})
}
}
I haven't tested this code, but this should guide you in the right direction :)

Related

How to update JQuery DataTables from Ajax Call [duplicate]

I am using plugin jQuery datatables and load my data which I have loaded in DOM at the bottom of page and initiates plugin in this way:
var myData = [
{
"id": 1,
"first_name": "John",
"last_name": "Doe"
}
];
$('#table').dataTable({
data: myData
columns: [
{ data: 'id' },
{ data: 'first_name' },
{ data: 'last_name' }
]
});
Now. after performing some action I want to get new data using ajax (but not ajax option build in datatables - don't get me wrong!) and update the table with these data. How can i do that using datatables API? The documentation is very confusing and I can not find a solution. Any help will be very much appreciated. Thanks.
SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).
CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:
The modern definition of DataTables (upper camel case):
var datatable = $( selector ).DataTable();
The legacy definition of DataTables (lower camel case):
var datatable = $( selector ).dataTable().api();
Using the new syntax.
var datatable = new $.fn.dataTable.Api( selector );
Then load the data like so:
$.get('myUrl', function(newDataArray) {
datatable.clear();
datatable.rows.add(newDataArray);
datatable.draw();
});
Use draw(false) to stay on the same page after the data update.
API references:
https://datatables.net/reference/api/clear()
https://datatables.net/reference/api/rows.add()
https://datatables.net/reference/api/draw()
You can use:
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
Jsfiddle
Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.
You need to destroy old data-table instance and then re-initialize data-table
First Check if data-table instance exist by using $.fn.dataTable.isDataTable
if exist then destroy it and then create new instance like this
if ($.fn.dataTable.isDataTable('#dataTableExample')) {
$('#dataTableExample').DataTable().destroy();
}
$('#dataTableExample').DataTable({
responsive: true,
destroy: true
});
Here is solution for legacy datatable 1.9.4
var myData = [
{
"id": 1,
"first_name": "Andy",
"last_name": "Anderson"
}
];
var myData2 = [
{
"id": 2,
"first_name": "Bob",
"last_name": "Benson"
}
];
$('#table').dataTable({
// data: myData,
aoColumns: [
{ mData: 'id' },
{ mData: 'first_name' },
{ mData: 'last_name' }
]
});
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).
My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).
Then I instantiate my table in the on load method
$(function () {
//.... some code here
table = $("#detailReportTable").DataTable();
.... more code here
});
and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:
function getOrderDetail() {
table.clear();
table.destroy();
...
$.ajax({
//.....api call here
});
....
table = $("#detailReportTable").DataTable();
}
I hope someone finds this useful!

Populating a grid using kendo js

I am working on a web app which needs to populate a grid with some data. I have a button wired with a onClick method which opens a new modal window for the grid to be displayed. I am using a jquery post call to the controller. However, I am unable to get the json data and assign it to my variable.
My code is as follows:
var grid_ds;
$.post('${ctx}/class/student/details?studentId=${student.studentId}', function(data){
}, 'json');
$('#student_grid').kendoGrid({
dataSource: grid_ds,
columns: [
{field: "studentName", title: "Student Name"},
{field: "studentClass", title: "Class"}
],
dataBound: function () {
emptyGrid($('#student_grid'));
}
}).data('kendoGrid');
My controller sends json back. I can see the data coming. How should I assign the json data to grid_ds and student_grid and make the values populate in the grid.
You could try using a kendo.data.DataSource with a custom transport function like so:
$('#student_grid').kendoGrid({
dataSource: dataSource = new kendo.data.DataSource({
transport: {
read: function (e) {
$.post('${ctx}/class/student/details?studentId=${student.studentId}', 'json')
.done(function (data) {
e.success(data);
});
}
}
}),
columns: [
{
field: "studentName",
title: "Student Name"
},
{
field: "studentClass",
title: "Class"
}
]});
I think the problem may be with how you're fetching the data. Since $.post is an ajax call operating out of band, grid_ds is most likely undefined when being passed to the .kendoGrid() function.
I wasn't able to locate the dataBound configuration property that you specify in your question in the kendo.ui.Grid. Do you happen to know where this configuration setting came from?

Automatically create header from JSON file, Bootstrap-table

I'm working with this bootstrap library and actually everything works fine. The question is, Can bootstrap-table generate header automatically in depend of JSON file? I've tried to find any information about that, but unlucky. Now my header is generated from script like from this example:
function initTable() {
$table.bootstrapTable({
height: getHeight(),
columns: [{
field: 'field1',
title: 'title1',
sortable: true
}, {
field: 'field2',
title: 'title2',
sortable: true
}, {
field: 'field3',
title: 'title3',
sortable: true
}, {
field: 'Actions',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
}
],
formatNoMatches: function () {
return "This table is empty...";
}
});
Does anyone how to generate header automatically?
Populating from a flat json file is definetly possible but harder than from a seperate (slimmer and preped) data request, because title and other attributes 'might' have to be guessed at.
Ill show basic approach, then tell you how to make it work if stuck with a flat file that you CAN or CANT affect the format of (important point, see notes at end).
Make a seperate ajax requests that populates var colArray = [], or passes direct inside done callback.
For example, in callback (.done(),.success(), ect) also calls to the function that contains the js init code for the table.
You might make it look something like this:
function initTable(cols) {
cols.push({
field: 'Actions',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
});
$("#table").bootstrapTable({
height: getHeight(),
columns: cols,
formatNoMatches: function () {
return "This table is empty...";
}
});
}
$(document).ready(function(){
$.ajax({
method: "POST",
url: "data/getColumns",
// data: { context: "getColumns" }
datatype: "json"
})
.done(function( data ) {
console.log( "getCols data: ", data );
// Prep column data, depending on what detail you sent back
$.each(data,function(ind,val){
data.sortable = true;
});
initTable(data);
});
});
Now, if you are in fact stuck with a flat file, point the ajax towards that then realise the question is whether you can edit the contents.
If yes, then add a columns array into it with whatever base data (title, fieldname, ect) that you need to help build your columns array. Then use responseHandler if needed to strip that columns array if it causes issues when loading into table.
http://bootstrap-table.wenzhixin.net.cn/documentation/#table-options
http://issues.wenzhixin.net.cn/bootstrap-table/ (click 'see source').
If no, you cant edit contents, and only have the fieldname, then look at using that in the .done() handler with whatever string operation (str_replace(), ect) that you need to make it look the way you want.

Select2 - Pass back additional data via ajax call

Ok, I feel like I'm going crazy here. I'm using the select2 jquery plugin (version 4), and retrieving data via ajax. So you can type in a name, and it will return that contact information. But I also want to return what organization that contact is a part of.
Here is my select2 initialization:
$('#contact_id').select2({
ajax: {
url: 'example.com/contacts/select',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 3,
maximumSelectionLength: 1
});
And here is the data I'm returning (laravel framework):
foreach($contacts as $con) {
$results[] = [
'id' => $con->contact_id,
'text' => $con->full_name,
'org' => [
'org_id' => $con->organization_id,
'org_name' => $con->org_name
]
];
}
return response()->json($results);
So isn't 'org' supposed to be attached to either the created option or select element by select2? So I could do something like $('#contact_id').select2().find(':selected').data('data').org or $('#contact_id').select2().data('data').org or something like that?
Idealistically, this would look like:
<select>
<option value="43" data-org="{org_id:377, org_name:'Galactic Empire'}">Darth Vader</option>
</select>
I swear I confirmed this worked last week, but now it's completely ignoring that org property. I have confirmed that the json data being returned does include org with the proper org_id and org_name. I haven't been able to dig anything up online, only this snippet of documentation:
The id and text properties are required on each object, and these are the properties that Select2 uses for the internal data objects. Any additional paramters passed in with data objects will be included on the data objects that Select2 exposes.
So can anyone help me with this? I've already wasted a couple hours on this.
EDIT: Since I haven't gotten any responses, my current plan is to use the processResults callback to spawn hidden input fields or JSON blocks that I will reference later in my code. I feel like this is a hacky solution given the situation, but if there's no other way, that's what I'll do. I'd rather that than do another ajax call to get the organization. When I get around to implementing it, I'll post my solution.
Can't comment for now (low reputation).. so... answering to slick:
Including additional data (v4.0):
processResults: function (data) {
data = data.map(function (item) {
return {
id: item.id_field,
text: item.text_field,
otherfield: item.otherfield
};
});
return { results: data };
}
Reading the data:
var data=$('#contact_id').select2('data')[0];
console.log(data.otherfield);
Can't remember what I was doing wrong, but with processResults(data), data contains the full response. In my implementation below, I access this info when an item is selected:
$('#select2-box').select2({
placeholder: 'Search Existing Contacts',
ajax: {
url: '/contacts/typeahead',
dataType: 'json',
delay: 250,
data: function(params){
return {
q: params.term,
type: '',
suggestions: 1
};
},
processResults: function(data, params){
//Send the data back
return {
results: data
};
}
},
minimumInputLength: 2
}).on('select2:select', function(event) {
// This is how I got ahold of the data
var contact = event.params.data;
// contact.suggestions ...
// contact.organization_id ...
});
// Data I was returning
[
{
"id":36167, // ID USED IN SELECT2
"avatar":null,
"organization_id":28037,
"text":"John Cena - WWE", // TEXT SHOWN IN SELECT2
"suggestions":[
{
"id":28037,
"text":"WWE",
"avatar":null
},
{
"id":21509,
"text":"Kurt Angle",
"avatar":null
},
{
"id":126,
"text":"Mark Calaway",
"avatar":null
},
{
"id":129,
"text":"Ricky Steamboat",
"avatar":null
},
{
"id":131,
"text":"Brock Lesnar",
"avatar":null
}
]
}
]

Select2 load JSON resultset via AJAX and search locally

Until now I've been using Select2's normal AJAX method of searching and filtering data serverside, but now I have a usecase where I want to retrieve all the results via AJAX when the select is opened and then use those results (now stored locally) to search and filter.
I've trawled the web looking for examples of how to do this and all i've found is lots of people saying the Query method should be used rather than the AJAX helper. Unfortunately I haven't found any examples.
So far all I've managed is the basic:
$('#parent').select2({
placeholder: "Select Parent",
minimumInputLength: 0,
allowClear: true,
query: function (query) {
//console.log(query);
query.callback(data);
}
});
data = {
more: false,
results: [
{ id: "CA", text: "California" },
{ id: "AL", text: "Alabama" }
]
}
Data is being passed to the select but query filtering is not implemented.
I'm struggling to understand the select2 documentation and would appreciate any assistance or links to examples.
Try the following - pre-load json data into local variable and when ready bind this to select2 object
<script>
function format(item) { return item.text; }
var jresults;
$(document).ready(function() {
$.getJSON("http://yoururl.com/api/select_something.json").done(
function( data ) {
$.jresults = data;
$("#parent").select2(
{formatResult: format,
formatSelection: format,
data: $.jresults }
);
}
)
});
</script>

Categories

Resources