How to give ajax success function response as input to datatables - json

I write a script code that calls the getdata.php by sending a value ,i am getting the success function response in json format it look like this.
my script code:
<script>
function getId(val) {
alert(val);
$.ajax({
type: "post",
url: "getdata.php",
data: 'id=' + val,
dataType: "JSON",
success: function(response){
console.log(response);
}
/*$('#city').dataTable({
"bProcessing": true,
"sAjaxSource": "JSON.parse(this.response)",
"aoColumns": [
{ mData: 'id' } ,
{ mData: 'vid' },
{ mData: 'date' },
{ mData: 'latitude' },
{ mData: 'longitude' },
{ mData: 'speed' },
{ mData: 'batery' },
{ mData: 'totalkm' },
{ mData: 'intrkm' },
{ mData: 'control' }
]
}); */
});
}
</script>
and my response json data :
{"sEcho":1,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[{"id":"1","vid":"A0001","date":"2019-02-07 15:58:53","latitude":"17.00","longitude":"82.20","speed":"25","batery":"98","totalkm":"8","intrkm":"8","control":"0"},{"id":"2","vid":"A0001","date":"2019-02-07 15:58:53","latitude":"17.10","longitude":"82.30","speed":"26","batery":"97","totalkm":"15","intrkm":"15","control":"0"}]}
console.log(response); gives like
{sEcho: 1, iTotalRecords: 2, iTotalDisplayRecords: 2, aaData: Array(2)}
aaData: Array(2)
0: {id: "1", vid: "A0001", date: "2019-02-07 15:58:53", latitude: "17.00",
longitude: "82.20", …}
1: {id: "2", vid: "A0001", date: "2019-02-07 15:58:53", latitude: "17.10",
longitude: "82.30", …}
length: 2
__proto__: Array(0)
iTotalDisplayRecords: 2
iTotalRecords: 2
sEcho: 1
Now, how to give the response of ajax call to datatables sAjax source and read the colums data and present it in #city.
please help me i am strucked here.

DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. This can be done, in its most simple form, by setting the ajax option to the address of the JSON data source.
$(document).ready(function() {
$('#city').DataTable( {
"ajax": 'getdata.php?any_value=1'
});
});
Refer more details : https://datatables.net/examples/data_sources/ajax

Related

JSON data from server could not be parsed. This is caused by a JSON formatting error

DataTables warning (table id = 'city'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.
my json data looks like this, I am trying to set the json data to data tables
{"sEcho":1,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[{"id":"1","vid":"A0001","date":"2019-02-07 15:58:53","latitude":"17.00","longitude":"82.20","speed":"25","batery":"98","totalkm":"8","intrkm":"8","control":"0"},{"id":"2","vid":"A0001","date":"2019-02-07 15:58:53","latitude":"17.10","longitude":"82.30","speed":"26","batery":"97","totalkm":"15","intrkm":"15","control":"0"}]}
i write a script code like this achieve that
<script>
function getId(val) {
$.ajax({
type: "post",
url: "getdata.php",
data: 'id=' + val,
dataType: "text",
success: function(response){
$('#city').dataTable({
"bProcessing": true,
"sAjaxSource": "getdata.php",
"aoColumns": [
{ mData: 'id' } ,
{ mData: 'vid' },
{ mData: 'date' },
{ mData: 'latitude' },
{ mData: 'longitude' },
{ mData: 'speed' },
{ mData: 'batery' },
{ mData: 'totalkm' },
{ mData: 'intrkm' },
{ mData: 'control' }
]
});
}
});
}
</script>
while doing this the datatable shows processing.... but not correctly loading datatables. I don't know whats wrong in it. Help me if any code has to change

ExtJS loading nested JSON data in grid

I have a php-script, which returns the following JSON
[
{
"Code":0,
"Message":"No problem"
},
{
"name":"o016561",
"status":1,
"locks":[
{
"ztn":"155320",
"dtn":"20131111",
"idn":"78"
},
{
"ztn":"155320",
"dtn":"20131111",
"idn":"91"
}
]
},
{
"name":"o011111",
"status":1,
"locks":[
{
"ztn":"155320",
"dtn":"20131111",
"idn":"91"
}
]
},
{
"name":"o019999",
"status":0,
"locks":[
]
},
{
"name":"o020000",
"status":0,
"locks":[
]
},
{
"name":"o020001",
"status":0,
"locks":[
]
}
]
Edit:
The grid should look something like this:
I've been able to load name and status into my grid - so far so good. But the more important part is, that I need the nested data in the locks-array being loaded into my grid, but I just can't get my code working. Any help would be appreciated.
I'm using ExtJS 4.2 if that matters.
Edit 2:
I tried
Ext.define("Locks", {
extend: 'Ext.data.Model',
fields: [
'ztn',
'dtn',
'idn'
]
});
Ext.define("ConnectionModel", {
extend: 'Ext.data.Model',
fields: ['name', 'status'],
hasMany: [{
model: 'Locks',
name: 'locks'
}]
});
var store = Ext.create('Ext.data.Store', {
model: "ConnectionModel",
autoLoad: true,
proxy: {
type: 'ajax',
reader: {
type: 'json',
root: 'name'
}
}
});
but it seemed to be wrong in multiple ways...
and it would be awesome if ztn and dtn could be displayed just seperated with a whitespace in the same column
You can add a renderer to the column. In that renderer you can do anything with the record...
Here's a working fiddle:
http://jsfiddle.net/Vandeplas/MWeGa/3/
Ext.create('Ext.grid.Panel', {
title: 'test',
store: store,
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Status',
dataIndex: 'status'
}, {
text: 'idn',
renderer: function (value, metaData, record, rowIdx, colIdx, store, view) {
values = [];
record.locks().each(function(lock){
values.push(lock.get('idn'));
});
return values.join('<br\>');
}
}, {
text: 'ztn + dtn',
renderer: function (value, metaData, record, rowIdx, colIdx, store, view) {
values = [];
record.locks().each(function(lock){
values.push(lock.get('ztn') + ' ' + lock.get('dtn'));
});
return values.join('<br\>');
}
}],
height: 200,
width: 600,
renderTo: Ext.getBody()
});
Note
If you have control over your backend you better change the form of your data more like this:
{
"code": 0,
"message": "No problem",
"success": true,
"data": [
{
"name": "o016561",
"status": 1,
"locks": [
{
"ztn": "155320",
"dtn": "20131111",
"idn": "78"
},
{
"ztn": "155320",
"dtn": "20131111",
"idn": "91"
}
]
},
{
"name": "o011111",
"status": 1,
"locks": [
{
"ztn": "155320",
"dtn": "20131111",
"idn": "91"
}
]
}
]
}
That way you don't mix your control data (success, message, code,...) with your data and the proxy picks it up correctly (it can be a cause of the problems your experiencing). I added a success boolean => Ext picks it up and goes to the failure handler. It helps a lot with your exception handling.
Here is the proxy for it:
proxy: {
type: 'ajax',
api: {
read: ___URL____
},
reader: {
type: 'json',
root: 'data',
messageProperty: 'message'
}
}

JSON.parse: unexpected character exception on jqgrid

I am getting a JSON.parse: unexpected character exception while I am trying to read a local JSON in my JQGrid.
<script type="text/javascript">
var jsondata = {
"totalpages": "1",
"currpage": "1",
"totalrecords": "2",
"invdata" : [
{"name":"New York City", "country":"USA", "continent":"NorthAmerica"},
{"name":"Paris", "country":"France", "continent":"Europe"}
]
};
$(document).ready(function() {
$("#grid").jqGrid({ data: jsondata,
datatype: "json",
colNames: ["Name", "Country", "Continent"],
colModel: [{
name: 'name',
index: 'name',
editable: true,
}, {
name: 'country',
index: 'country',
editable: true,
}, {
name: 'continent',
index: 'continent',
editable: true,
}],
pager: '#pager',
jsonReader : {
root:"invdata",
page: "currpage",
total: "totalpages",
records: "totalrecords",
repeatitems: false,
id: "0"
},
caption:"Dynamic hide/show column groups"
}).navGrid("#pager",{edit:false,add:false,del:false});
jQuery("#hc").click( function() { jQuery("#grid").jqGrid('hideCol',["continent"]); });
jQuery("#sc").click( function() { jQuery("#grid").jqGrid('showCol',["continent"]); });
});
</script>
I have tried to lookup in the jqgrid Wiki but still unable to figure out what's wrong. Is there a problem with the jsonReader? I have checked related questions but it didn't help much.
Instead of giving "jsondata" as a parameter to "data" for the jqgrid, give data : jsondata.invdata

Sencha Touch 2.2 load store from JSON, data goes to raw column

I'm trying to load a store from JSON received from webservices. But all the data from the JSON goes under the 'raw' column of the items in the store...
I can't figure out why, my code seems correct.
Any help is welcome.
My Model :
Ext.define('App.model.Node', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'int' },
{ name: 'version', type: 'int' },
{ name: 'user_id', type: 'int' },
{ name: 'tstamp', type: 'date' },
{ name: 'changeset_id', type: 'int' },
{ name: 'tags', type: 'string' },
{ name: 'geom', type: 'string'}
],
idProperty: 'id'
}
});
My Store :
Ext.define('App.store.NodeStore', {
extend: 'Ext.data.Store',
xtype: 'nodestore',
requires: [
'Ext.data.proxy.Rest'
],
config: {
model: 'App.model.Node',
storeId: 'nodeStore',
autoLoad: true,
proxy: {
type:'rest',
url:'http://localhost/server/nodes',
reader: {
type:'json',
rootProperty: 'nodes'
},
noCache: false,
limitParam: false,
headers: {
'Accept' : 'application/json'
}
}
}
});
My JSON :
{
"nodes": [
{
"id": "454467",
"version": 6,
"user_id": 52015,
"tstamp": "2008-12-27 21:38:45",
"changeset_id": "634766",
"tags": "",
"geom": "0101000020E6100000409CD1A0B29321405455682096804740"
},
{
"id": "454468",
"version": 8,
"user_id": 52015,
"tstamp": "2009-12-23 20:47:15",
"changeset_id": "3437205",
"tags": "",
"geom": "0101000020E6100000357C0BEBC69321409EC02ACD9C804740"
},
{
"id": "454469",
"version": 7,
"user_id": 52015,
"tstamp": "2009-12-23 20:47:15",
"changeset_id": "3437205",
"tags": "",
"geom": "0101000020E6100000347914F8D4932140B8BBBD5AA4804740"
}
]
}
And when I do a
var nodeStore = Ext.getStore('nodeStore');
nodeStore.load();
console.log(nodeStore.getData());
we can see the following object, with my data in the raw column under items...
I figured it out, my code is correct and the only thing missing is a callback in the load() function :
nodeStore.load({
callback: function(records, operation, success) {
console.log(records);
console.log(nodeStore.getCount());
nodeStore.each(function(element) {
console.log(element.data.id);
});
},
scope: this,
});
The problem was I was trying to access the store before it loaded the data. Now I'm waiting that all the data is loaded to access it, and it works.

jqGrid JSON - Why doesn't jqGrid like this JSON? And can someone please provide the script and markup that will work with this string?

Here's the JSON:
{
"page": "1",
"total": "1",
"records": "2",
"rows": [
{
"Id": 3,
"FirstName": "Test",
"LastName": "Testerson",
"CustomerNumber": "1234",
"EmailAddress": "test#test.com",
"Subject": "Test1",
"OrderNumber": "4321",
"Comments": "This is a test"
},
{
"Id": 4,
"FirstName": "Test2",
"LastName": "Testerson2",
"CustomerNumber": "2222",
"EmailAddress": "test#test.com",
"Subject": "Test1",
"OrderNumber": "3333",
"Comments": "This is a test"
}
]
}
Here's my current script and markup (why isn't this working?):
<table id="list1"></table>
<div id="pager1"></div>
<script type="text/javascript">
function getData(pdata) {
var params = new Object();
params.page = pdata.page;
params.pageSize = pdata.rows;
params.sortIndex = pdata.sidx;
params.sortDirection = pdata.sord;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScriptServices/PNScriptService.asmx/GetContactRequests",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#list1")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert('An error has occured retrieving the data.');
}
});
}
$(document).ready(function () {
$("#list1").jqGrid({
datatype: function (pdata) {
getData(pdata);
},
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
id: "Id",
repeatitems: false
},
colNames: ['Id', 'FirstName', 'LastName', 'CustomerNumber', 'EmailAddress', 'Subject', 'OrderNumber', 'Comments'],
colModel: [
{ name: 'Id', index: 'Id', width: 90 },
{ name: 'FirstName', index: 'FirstName', width: 100 },
{ name: 'LastName', index: 'LastName', width: 100 },
{ name: 'CustomerNumber', index: 'CustomerNumber', width: 80, align: "right" },
{ name: 'EmailAddress', index: 'EmailAddress', width: 100 },
{ name: 'Subject', index: 'Subject', width: 80 },
{ name: 'OrderNumber', index: 'OrderNumber', width: 80, align: "right" },
{ name: 'Comments', index: 'Comments', width: 250, sortable: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: $('#pager1'),
sortname: 'Id',
viewrecords: true,
sortorder: "desc",
caption: "Contact Requests"
});
});
</script>
btw: The JSON string above is the exact string returned by the script service. I can hit a break point in my script service and grab that string, and I can alert the string in the calling ajax script on success, and the strings are identical. So I know it's not the script service, and I know that that json string is being passed, as shown, into the jqGrid.
Your problem is that you user very very old template code for loading JSON data. If your server produce the JSON data which you posted you can simplify for code to the following.
In another answers you will find more code examples in case you use ASMX, which produce a litle other JSON code as you posted.
Thanks Oleg for the info, but it turned out to be the following:
thegrid.addJSONData(JSON.parse(data.d));
I needed to JSON.parse the data before passing it into the grid.