Struggling to bind JSON data - JQuery Datatables - json

I am struggling to bind the JSON data into a Datatable. This is my Javascript code.
$.ajax({
type: "POST",
data: $('#searchForm').serialize(),
url: "/ReportingItem/Search",
success: function (data) {
$('#searchResults').DataTable({
data: data,
dataSrc: "",
columns: [
{ "data": "ID" },
{ "data": "ItemContent" }
]
});
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
This is my JSON
"[{"ID":"3","ItemContent":"2nd Test"},{"ID":"4","ItemContent":"3rd Test"},{"ID":"9","ItemContent":"eeeeee"},{"ID":"11","ItemContent":"aaaa"}]"
You can see its a flat array. therefore I have used dataSRC="" so it doesn't look for "data" in the JSON
This is the error message I am getting
DataTables warning: table id=searchResults - Requested unknown
parameter 'ID' for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4
Any help on the Syntax would be helpful!
Thanks
Chris

Just add in the data line
$('#searchResults').DataTable({
data: JSON.parse(data),
....
});
JSON.parse

Just you have to check what json objects return in ReportingItem/Search.
as you mention:
"[{"ID":"3","ItemContent":"2nd Test"},{"ID":"4","ItemContent":"3rd Test"},{"ID":"9","ItemContent":"eeeeee"},{"ID":"11","ItemContent":"aaaa"}]"
in most case json format is camel notation format. it means object names start with lowercase. so you should make some changes in WebApiConfig or if its not api in a config which you set : ReportingItem/Search
add this to the method Register:
using System.Web.Mvc;
using System.Web.Routing;
public static void Register(HttpConfiguration config)
{
var Settings = config.Formatters.JsonFormatter.SerializerSettings;
Settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Settings.Formatting = Formatting.Indented;
//... other codes
}
at the end instead of
columns: [
{ "data": "ID" },
{ "data": "ItemContent" }
]
use this:
columns: [
{ "data": "iD" },
{ "data": "itemContent" }
]
hope its done.

Related

Filing Bootstrap Datatable from remote JSON file

I am trying to fill the table (Bootstrap datatable) with the data from remote JSON file.
JSON file is located at https://ba.ekapija.com/company/tender-winner-json/103510/pobede-na-tenderima?hash=28cd4a0e334aec8f84a94f30bb340e7f
And this is the function I use:
$(document).ready( function() {
$('#twodotsmediatable').dataTable( {
"data": "https://ba.ekapija.com/company/tender-winner-json/103510/pobede-na-tenderima?hash=28cd4a0e334aec8f84a94f30bb340e7f",
"columns": [
{ "data": "tender" },
{ "data": "url" },
{ "data": "date" },
{ "data": "amount" },
{ "data": "company" },
{ "data": "address" }
]
} );
$('.dataTables_length').addClass('bs-select');
});
I have also tried with:
"ajax": "https://ba.ekapija.com/company/tender-winner-json/103510/pobede-na-tenderima?hash=28cd4a0e334aec8f84a94f30bb340e7f"
But with no luck in both cases. Please help me to find where am I making mistake.
You should always use ajax.url :
$('#twodotsmediatable').dataTable( {
ajax: {
url: 'https://ba.ekapija....'
},
columns: [ .. ]
})
You cannot overcome request blocking in the browser, but you can get the desired JSON through a serverside proxy. If your server support PHP a proxy.php could look like this :
<?
echo file_get_contents($_GET['url']);
?>
Get data via proxy :
$('#twodotsmediatable').dataTable( {
ajax: {
url: 'proxy.php?url=https://ba.ekapija....',
dataSrc: function(d) {
return d[0];
}
},
columns: [ .. ]
})
NB: Use of dataSrc is needed since the JSON seem to be on the form [[{ item, item, .. } ]]

Load multiple JSON object

I am trying to load multiple JSON object from one file, but my attempts failed.
Here is my code which run to error when I tried to load .JSON file.
$(document).ready(function(){
$.ajax({
url: "..data.json",
method: "GET",
success: function(data) {
// do something
},
error: function(data) {
console.log('error');
}
});
});
The file format what I am trying to load is the following:
[{"id_first":"1","data_first":"1"},{"id_first":"2","data_first":"2"}] [{"id_second":"1","data_second":"1"},{"id_second":"2","data_second":"2"}]
Is there any solultion for this problem? Thanks for helps in advance!
i think you need to change the json schema like this at the backend.
[
[{
"id_first": "1",
"data_first": "1"
}, {
"id_first": "2",
"data_first": "2"
}],
[{
"id_second": "1",
"data_second": "1"
}, {
"id_second": "2",
"data_second": "2"
}]
]
it more easier for you to process the data.

I try to generate output the json string return from php but i cant do it

tthe following is my json string return from php and suggest me how i can get value from following json string.
[
{
"picid": "13",
"itemcode": "P-0000001",
"filename": "-1970-01-011.jpg",
"primarystatus": "active"
},
{
"picid": "16",
"itemcode": "P-0000001",
"filename": "dateArray1.jpg",
"primarystatus": "active"
},
{
"picid": "18",
"itemcode": "P-0000001",
"filename": "dateArray3.jpg",
"primarystatus": "active"
},
{
"picid": "19",
"itemcode": "P-0000001",
"filename": "dateArray4.jpg",
"primarystatus": "active"
}
]
//php
function returnALLPic()
{
if(isset($_POST['id']))
{
$data= $this->m_phone->getAllPictureInformation($_POST["id"]);
$ss= json_encode($data);
echo $ss;
}
}
//jquery
$.ajax({
type: 'POST',
url: 'http://localhost/tt/index.php/ad_access/c_r/returnALLPic',
data: 'id='+ei,
success: function(msg)
{
// console.log(JSONObject); // Dump all data of the Object in the console
$('#model').html(msg[0].itemcode)
}
});
You can parse json using following code.
var json = $.parseJSON(j);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
You can do this in PHP as well.
Read this using
$data = file_get_contents('Your_URL')
and then use following function to parse it
$phpArray = json_decode($data);
You can do what ever you want do with that
If you need to output in php, use json_decode()
then get what you want from the loop
$sss= json_decode($data)

express.js 4 JSON parsing problems from GET request (request data from datatables)

I am having problems parsing a serialized JSON Ajax Get request (using jQuery $.ajax) send to my express.js 4 server. The data send as a JSON request is generated by datatables.
Here is how I started on the client-side
$(document).ready(function() {
$('#example').dataTable( {
"bServerSide": true,
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
contentType: 'application/json',
"type": "GET",
"url": "http://localhost:3000/ajax/phenotypes/withOrg/like/datatables/",
"data": aoData,
"success": fnCallback,
"error": function () {
alert('have some problem');
}
});
}
} );
} );
when I load this code in the brower datatables generates the following GET request URL (to the server):
GET
/ajax/phenotypes/withOrg/like/datatables/?draw=1&columns=%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D&order=%5Bobject+Object%5D&start=0&length=10&search=%5Bobject+Object%5D
or in decoded form (output from firebug)
columns [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
draw 1
length 10
order [object Object]
search [object Object]
start 0
so I serialized the data before sending
$(document).ready(function() {
$('#example').dataTable( {
"bServerSide": true,
"fnServerData": function (sSource, aoData, fnCallback) {
var myData = JSON.stringify(aoData);
$.ajax({
"dataType": 'json',
contentType: 'application/json',
"type": "GET",
"url": "http://localhost:3000/ajax/phenotypes/withOrg/like/datatables/",
"data": myData,
"success": fnCallback,
"error": function () {
alert('have some problem');
}
});
}
} );
} );
here is the generated GET parameters from datatables:
GET
/ajax/phenotypes/withOrg/like/datatables/?[{%22name%22:%22draw%22,%22value%22:1},{%22name%22:%22columns%22,%22value%22:[{%22data%22:0,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:1,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:2,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:3,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:4,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:5,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}}]},{%22name%22:%22order%22,%22value%22:[{%22column%22:0,%22dir%22:%22asc%22}]},{%22name%22:%22start%22,%22value%22:0},{%22name%22:%22length%22,%22value%22:10},{%22name%22:%22search%22,%22value%22:{%22value%22:%22%22,%22regex%22:false}}]
HTTP/1.1
in decoded form (output from firebug and beautified using an online tool- checked with jslint, seems correct!)
[
{
"name":"draw",
"value":1
},
{
"name":"columns",
"value":[
{
"data":0,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":1,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":2,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":3,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":4,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
},
{
"data":5,
"name":"",
"searchable":true,
"orderable":true,
"search":{
"value":"",
"regex":false
}
}
]
},
{
"name":"order",
"value":[
{
"column":0,
"dir":"asc"
}
]
},
{
"name":"start",
"value":0
},
{
"name":"length",
"value":10
},
{
"name":"search",
"value":{
"value":"",
"regex":false
}
}
]
the problem is now that this stringified URL can not be parsed on the express 4 server side
I use express4 req.query and url.parse method for this : http://expressjs.com/api.html#req.query
and then try to parse the received json string with the JSON.parse() method
...
var url = require('url');
...
router.get('/withOrg/like/datatables/', function (req, res) {
console.log('getting json string via req.query');
console.log(req.query);
console.log('output parsed json object using JSON.parse');
console.log(JSON.parse(req.query));
//another try
console.log('for stack overflows test 2');
console.log(url.parse(req.url, true).query);
console.log('output parsed json object using JSON.parse');
console.log(url.parse(req.url, true).query);
})
both json string output results are invalid json as you can see here and unable to parse with JSON.parse:
getting json string via req.query
{
'{"data":0,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":1,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":2,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":3,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":4,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":5,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}':
{ '{"column":0,"dir":"asc"}': '' } }
output parsed json object using JSON.parse
getting json string via req.query
{
'{"data":0,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":1,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":2,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":3,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":4,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":5,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}':
{ '{"column":0,"dir":"asc"}': '' } }
output parsed json object using JSON.parse
when I try to parse the json string I get the error from JSON.parse
SyntaxError: Unexpected token o
at Object.parse (native)
at module.exports (/Users/xxx/yyy/routes/phenotypesAJAX.js:16:19)
at Layer.handle [as handle_request] (/Users/xxx/yyy/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/xxx/yyy/node_modules/express/lib/router/route.js:100:13)
Is this a bug in express 4?
I cannot see where the problem is. On the client-side the serialized datatable GET request seems valid (checked with JSLint). On the express4 server side I cannot find any other way to parse the GET request in a different way.
Thank you so much for your help,
Oliver
I have got the answer from posting this problem at the express github bugtracker.
Lesson learned:
I was thinking to complicated, express.js request methods are not written especially for a specific request format! They just use the data format which was send to them without modification!
The method I used first:
req.query
[..] only works with standard query strings, which are key=value pairs,
which the URL you gave was not.[..]
The correct method to solve my problem is:
url.parse(req.url).query
returns the complete parameter string of an URL which than has to be decoded manually:
obj = JSON.parse(decodeURIComponent(query))
Here is the full explanation:
https://github.com/strongloop/express/issues/2460

Backbone JS parse json attribute to a collection's model

I'm having trouble parsing a json to a model.
Here is the JSON:
[
{
"name": "Douglas Crockford",
"email": "example#gmail.com",
"_id": "50f5f5d4014e045f000002",
"__v": 0,
"items": [
{
"cena1": "Cena1",
"cena2": "Cena2",
"cena3": Cena3,
"cena4": "Cena4",
"cena5": "Cena5",
"cena6": Cena6,
"_id": "50ee3e782a3d30fe020001"
}
]
}
]
And i need a model to have the 'items' attributes like this:
cena = new Model({
cena1: "Cena1",
cena2: "Cena2",
...
});
What I've tried:
var cenaCollection = new Backbone.Collection.extend({
model: Cenas,
url: '/orders',
parse: function (response) {
return this.model = response.items;
}
});
then I create new instance of the collection and fetch, but i get "response.items" always "undefined" :|
Thanks in advance!
The parse function should return the attributes hash to be set on the model (see the documentation here). So you'll need simply:
parse: function (response) {
return response[0].items;
}