jquery Datatables using JSON - javascript

I am using datatables jQuery plugin to show the data nicely withing a table. I am making an ajax request on a click of a button which is then running a php script returning a JSON.
Here's how my code:
$('#searchInSugar').button().on('click', function (e) {
var searchTxt = $('#searchEntry').val();
var moduleName = $('#moduleSelect').val();
if (!searchTxt.trim() || searchTxt.length === 0) {
alert("Please provide some search text string..");
return false;
}
if (moduleName === "select") {
alert("Please select a module..");
return false;
}
$.ajax({
type: 'POST',
url: "fetch_records.php",
data: {"searchText": searchTxt,
"module": moduleName},
success: function (data) {
obj = JSON.parse(data);
$(document).ready(function () {
$('#dialog_entry_table').DataTable({
"info": false,
data: data,
columns: [
{"records": "id"},
{"records": "name"},
{"records": "account_name"}
]
});
});
},
error: function (exception) {
alert('Exeption:' + exception);
}
});
});
Here's the json that I get from the php script.
{
"next_offset":-1,
"records":[
{
"id":"a54e81f8-72b2-ae9b-d526-5608761a28e8",
"name":"Mr. James Smith",
"date_modified":"2015-09-27T23:52:29+00:00",
"account_name":"",
"_acl":{
"fields":{
}
},
"_module":"Contacts"
},
{
"id":"b8ec2e0a-ade1-f70f-d722-56098e5c4370",
"name":"james bond",
"date_modified":"2015-09-28T22:50:56+00:00",
"account_name":"",
"_acl":{
"fields":{
}
},
"_module":"Contacts"
},
{
"id":"4de93888-155c-7e59-9c4b-56058f1b7ce9",
"name":"Mr. James Bond",
"date_modified":"2015-09-28T01:50:49+00:00",
"account_name":"OSSG",
"_acl":{
"fields":{
}
},
"_module":"Contacts"
}
]
}
Now, I ONLY WANT TO SHOW id, name and account_name IN THE TABLE, But I am having a hard time achieving this, could someone help/advise what I am doing wrong here.
This is the error I am getting:

Try:
var dt = [];
$.each(data.records,function(i,v) {
dt.push([v.id,v.name,v.account_name]);
});
$('#dialog_entry_table').DataTable({
"info": false,
data: dt,
columns: [
{"title": "id"},
{"title": "name"},
{"title": "account_name"}
]
});
jsfiddle: https://jsfiddle.net/bwqfq2gr/1/

Related

How to pass the path of my JSON using JStree? Can I use /create another treeview CRUD?

I'm using Jstree and trying to put my JSON to the code using a method who I created that get the path to the JSON but I don't have any success. Have another way using just ASP.net core to create a CRUD viewtree without using Jstree? If don't have, how can I make it works?
The code:
let data_2 = #Html.Raw(Json.Serialize(Model.texto2));
var teste = decodeURIComponent("#Html.Raw(Model.getFile())");
window.location = teste;
$(document).ready(function (){
//parte do ajax
//fim ajax
var dataJson = JSON.parse(data_2);
$('#html1').jstree(
{
"core": {
"themes": {
"variant": "large"
},
"max_children":2
},
"plugins": ["contextmenu", "dnd", "search",
"state", "types", "wholerow"],
"root": {
"valid_children": ["default"]
}
}
);
$('#html2').jstree(
{
"core": {
"themes": {
"variant": "large"
},
"max_children":2
},
"plugins": ["contextmenu", "dnd", "search",
"state", "types", "wholerow"],
"json_data": {
"ajax": {
"url": "",
"data": function (n) {
return {
id: n.attr ? n.attr("id") : 0
}
}
}
}
);
});
I tried to put my JSON (a simple JSON just to make it works firstly) into JStree to make a CRUD with the framework.
{
"root": {
"branche": "example"
}
}
Update: i finally solved my first problem! but now i have another problem:I need to transform that path (the get file()) into a URL path. How can i do it? The new edit:
$('#html2').jstree // "#Html.Raw(Model.getFile().Replace(#"\", "/"))", <-- the data
(
{
"core": {
"themes": {
"variant": "large"
},
'data':{
type: "POST",
url: "#Html.Raw(Model.getFile().Replace(#"\", "/"))",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
}
}
}
);

DataTable Range Datetime Filter

I've a datatable which i fill with ajax response. In the response i'm getting a string date data. I can write that data on datatable but i can't filter the data with date range. I've try so much way but i can't solve this. some of my trying i get " fnDraw()" is not function or some error like this. how can I make the range filter ?
JavaScrıpt code :
$(document).ready(function () {
var table = $.ajax({
type: "GET",
url: '/History/GetCallbackHistory',
data: { UserId: document.getElementById("callbackuserid").value },
dataType: 'json',
success: function (obj, textstatus) {
$('#callback_table').DataTable({
"pagingType": "input",
"language":
{
"processing": "<div class='loader'>Loading...</div>",
"paginate": {
"previous": "",
"next": ""
},
},
dom: "<'row'<'container-c'pi<'permuheader'<'refresh-button'>><'tlength'l>>>"
+ "<'row'>"
+ "<'row'<'col-sm-12't>r>",
data: obj,
columns: [
{
"data": "Id"
},
{
"data": "DateCallback"
},
{
"data": "callbackId"
},
{
"data": "Task_name"
},
{
"data": "callbackStatus"
},
{
"data": "Point"
},
{
"data": "TransactionType"
},
{
"data": "DateEnd"
}
]
});
},
error: function (obj, textstatus) {
alert(obj.msg);
}
});
$("#datepicker_from").datepicker({
showOn: "button",
buttonImageOnly: false,
"onSelect": function (date) {
minDateFilter = new Date(date).getTime();
table.fnDraw();
}
}).keyup(function () {
minDateFilter = new Date(this.value).getTime();
table.fnDraw();
});
$("#datepicker_to").datepicker({
showOn: "button",
buttonImageOnly: false,
"onSelect": function (date) {
maxDateFilter = new Date(date).getTime();
table.fnDraw();
}
}).keyup(function () {
maxDateFilter = new Date(this.value).getTime();
table.fnDraw();
});
});
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
if (typeof aData._date == 'undefined') {
aData._date = new Date(aData[1]).getTime();
}
if (minDateFilter && !isNaN(minDateFilter)) {
if (aData._date < minDateFilter) {
return false;
}
}
if (maxDateFilter && !isNaN(maxDateFilter)) {
if (aData._date > maxDateFilter) {
return false;
}
}
return true;
}
);
When you use jQuery's ajax like this:
var table = $.ajax({ ... });
You are assigning the jQuery object to your table variable. You are not assigning the DataTable from the success function to the table variable.
This is why, when you try to use table.fnDraw(), you get that specific error: Your table is not a DataTable. The ajax call is asynchronous - it does not return anything from the success call in the normal flow of your code.
Instead, the simplest alternative that I would recommend is to re-arrange your code to use DataTables' built-in support for ajax.
In this new approach we do not need to use the jQuery ajax function at all - so we completely remove that from the code. Instead, we do this:
var table = $('#callback_table').DataTable({
"ajax": {
"method": "GET",
"url": "/History/GetCallbackHistory",
"data": {
UserId: document.getElementById("callbackuserid").value
},
"dataType": "json",
"dataSrc": ""
},
"pagingType": "input",
"language": {
"processing": "<div class='loader'>Loading...</div>",
"paginate": {
"previous": "",
"next": ""
},
},
"dom": "<'row'<'container-c'pi<'permuheader'<'refresh-button'>><'tlength'l>>>" +
"<'row'>" +
"<'row'<'col-sm-12't>r>",
"columns": [{
"data": "Id"
},
{
"data": "DateCallback"
},
{
"data": "callbackId"
},
{
"data": "Task_name"
},
{
"data": "callbackStatus"
},
{
"data": "Point"
},
{
"data": "TransactionType"
},
{
"data": "DateEnd"
}
]
});
The main point to note is the ajax section:
"ajax": {
"method": "GET",
"url": "/History/GetCallbackHistory",
"data": {
UserId: document.getElementById("callbackuserid").value
},
"dataType": "json",
"dataSrc": ""
},
This is a wrapper around the jQuery ajax function. But it also uses a DataTables extension to jQuery's ajax: the dataSrc option. This option replaces your old data: obj option. It tells DataTables that your JSON response is a plain array.
Once you have done this, then your table variable will contain a valid DataTables object - and you can now use table.fnDraw();. But it would be better to use the modern name for this function: table.draw();.
If you have filtering problems, after that, you can refer to the official date range filtering example DataTables date range filter, to make sure your approach matches the example's approach (but using your preferred datepicker controls).

Create datatable in js via json data in a variable?

now I encounter a problem. I want to use ajax to show a datatable via using data coming from sql server database. Current state is I have used ajax to call a Handler.ashx to connect sql server and convert the data to json (using newtonsoft.json). In ajax, all json data has been recevied from Handler.ashx and stored in a variable "msg" which could be successfully showed on page. I want to put this "msg" into a datatable but failed all the time. I tried almost all methods online to set the datatable but still give different errors. I want to create a datatable in js and fill in my json data. But the result is either null or no data available in table.
Here is the codes and json data looks like.
js:
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
//contentType: "application/json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
cache: false,
success: function (msg) {
//for (var i in msg) {
// $("#eventGrid").append(msg[i]);
//}
//var jsonStr = JSON.stringify(msg);
document.getElementById("result").innerHTML = msg;
$('#eventtable').dataTable({
//"paging": false,
//"searching": false,
//"retrieve": true,
//"bProcessing": true,
//"data": msg.data,
//"datatype": "JSON",
//"ajax": "HandlerAll.ashx",
//"aaData": JSON.parse(msg),
//"ajax":
//"dataSrc":virtualTable
//"aoColumns": [
// { "mData": "ID" },
// { "mData": "FESTIVAL" },
// { "mData": "SUBURB" },
// { "mData": "POSTCODE" },
// { "mData": "WEBSITE" },
// { "mData": "DESCRIPTION" }
// ]
});
},
error: function (data) {
alert("Server error.");
}
})
});
});
json data (the size depends on the search condition, the table columns should have "ID","Festival" and so on, but no "virtualTable"):
{ "virtualTable": [ { "ID": "1", "FESTIVAL": "Antipodes Festival", "SUBURB": "Lonsdale Street, Melbourne", "POSTCODE": "3000", "WEBSITE": "http://www.antipodesfestival.com.au/", "DESCRIPTION": "The greek precinct in melbourne cbd will transform into a huge, free street festival with the hosting of the antipodes lonsdale street festival which will hold sway from 14 february 2015 to 15 february 2015." }, { "ID": "5", "FESTIVAL": "Boite Singers Festival", "SUBURB": "Victoria", "POSTCODE": "3000", "WEBSITE": "http://boite.com.au/index.php", "DESCRIPTION": "The boite singers festival brings you four days of vocal inspiration and sheer fun on the second weekend of january each year." } ] }
Since you get a JSON as reponse, I would try to convert it to JSON object, take the virtualTable part that it is a set of records in JSON and convert it to an array to add it to my table.
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
// dataType: "json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
success: function (msg) {
var jdata = $.parseJSON(msg);
jdata = jdata.virtualTable;
if (jdata.length != 0) {
var array_data = [];
var temp_array = [];
$(jdata).each(function(key, value) {
temp_array = [];
temp_array = [value.ID,
value.FESTIVAL,
value.SUBURB,
value.POSTCODE,
value.WEBSITE,
value.DESCRIPTION
];
array_data[array_data.length] = temp_array;
});
$('#eventtable').dataTable().fnAddData(array_data);
$('#eventtable').dataTable().fnDraw();
},
error: function (data) {
alert("Server error");
}
SOLUTION
Use the code below to initialize the table:
$('#eventtable').dataTable({
data: msg.virtualTable,
columns: [
{ data: "ID" },
{ data: "FESTIVAL" },
{ data: "SUBURB" },
{ data: "POSTCODE" },
{ data: "WEBSITE" },
{ data: "DESCRIPTION" }
]
});
DEMO
See this jsFiddle for code and demonstration.

Ext JS Read JSON response before reader in Store

I have JSON response as below -
{
"success": true,
"data": {
"data": [
{
"resultsMap": {
"Title": "Test1",
"Name": "Test1"
},
"id": 1
},
{
"resultsMap": {
"Title": "Test2",
"Name": "Test2"
},
"id": 2
}
],
"total": 2
}
}
I am using a custom reader to extract the data. Problem is I loose the initial JSON response from the server from which I need to extract the "total". Can someone help me in getting the "total" from the json response?
var newStore = Ext.create('Ext.data.BufferedStore', {
pageSize: 2000,
fields:fields,
//leadingBufferZone:50,
//trailingBufferZone:50,
//autoLoad: {start: 0, limit: 2000},
remoteSort: true,
sorters: [{
property : 'name',
direction: 'asc'
}],
proxy: {
type: 'ajax',
url: 'getData.json',
reader: {
type: 'nestedjsonreader',
rootProperty: 'data',
totalProperty: function(data) {
//console.log(data);
return data.totalCount;
},
},
extraParams: {
id:ID
}
},
listeners: {
'load' : function(store, records, success, options){
//the complete response
console.log(store.getProxy().getReader().rawData);
}
}
});
Ext.define('Portal.model.NestedJsonReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.nestedjsonreader',
readRecords: function(data) {
var arr = data.data.data;
var data = [];
if(arr!=undefined){
for(var i=0;i<arr.length;i++){
var obj = arr[i].resultsMap;
data.push(obj);
}
}
return this.callParent( [ data ]);
}
})
Create a custom property in your store as resp_total and assign data.total to it.

loading data in datatable on onchange event

I want to implement function in which data will be loaded into datatable after onChange event. So for that I am trying to implement code as below.
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
Which is creating my datatable layout and I am calling below function on dropdown change event is :
function loadFeedback(){
viewdatatabJS = $('#dataTablesFeedback').dataTable({
"processing" : true,
"retrieve" : true,
"ajax" : "/nhp/rest/feedback/viewFeedback",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "userName", "value":employeeId } ,
{ "name": "resourceId", "value":mentorDataJson[$('#dropDownId').val()].resourceId });
},
});
}
Where I am passing some parameter in aoData.push but my URL is not getting called.
I Solved the issue by simply implementing datatable properties. i wrote my code of datatable
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
in jsp document.ready(function()) and then on my request call of drop down change event i wrote below code on my javascript function.
$.ajax({
url : "",
type: 'GET',
contentType: "application/json",
data: {
'userName': value,
'resourceId' : value,
},
success: function(data) {
var table = $('#dataTablesFeedback').DataTable();
table.clear();
table.rows.add(data.data);
table.draw();
});
this way i first clear my datatable and then redraw it using my json which i got from my ajax call.
Thanks

Categories

Resources