Datatable Invalid JSON response - javascript

I have a problem with Datatables.
Until now, everything worked like a charm, now, from reasons unknown to me, datatables stopped working on my app.
My datatable ajax call is returning:
DataTables warning: table id=section-list - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
My datatables init:
sections.find('table#section-list').dataTable({
"ajax": '/admin/page/get-section-list',
"columns": [
{"data": "SectionID"},
{"data": "SectionAlias"},
{"data": "Edit"},
{"data": "Delete"},
], aoColumnDefs: [
{
bSortable: false,
aTargets: [-1, -2, -3] // disable sorting on last three columns (icons)
}
]
});
and my page/get-section-list action
....
return new JsonModel(["data" => $sections]); // this is equivalent to echo json_encode() in basic php
I tested my JSON in Json Parser AND it is 100% ok and there is no previous output before this json.
Im using DataTables 1.10.3 with jQuery v1.10.2

I ran into a similar problem working with a data.json file and found the information from here very helpful. Specifically the recommendation to open chrome dev tools, click the network tab, and then try the request again so you can see it in the network timeline.
In my case it looked like the json file in my "ajax": '/path/to/data.json' was still being written to at the same time the reload request was trying to access the data. Adding a delay around the reload request to give data.json time to complete solved the issue:
setTimeout(
function() {
$('#tableid').DataTable().ajax.reload(null, false);
}, 125);
But its hard to know what the optimal delay setting should be. So instead of doing the settimeout() (which works btw), I changed how I was writing my data from nodejs asynchronous fs.writeFile() to the synchronous fs.writeFileSync() when writing to the file.
Every case will be a little different but if you know the data source normally returns valid json, you may want to inspect if that source is changing at the same time datatables is trying to access it.

Related

Issue with JSON.parse , don't know why is not parsing everything

I'm developing a web app with Node.js using Sails framework(based on Express) and i'm using a third party image solution called Transloadit (no need to know Transloadit).
Anyway, that's not the problem, i'm been able to implement the Transloadit form and receive the information from their API.
My problem is that, Transloadit gives me the response as a String, and I need to access the response objects, so i'm using var objRes = JSON.parse(req.body.transloadit); to parse it to an JSON object, and when I console.log(objRes); the object is not correctly parsed, i get this: (see all JSON here https://gist.github.com/kevinblanco/9631085 )
{
a bunch of fields here .....
last_seq: 2,
results: {
thumb: [
[
Object
]
]
}
}
And I need the data from the thumb array, my question is, Why is doing that when parsing ?
Here's the entire request req.body object: https://gist.github.com/kevinblanco/9628156 as you can see the transloadit field is a string, and I need the data from some of their fields.
Thanks in advance.
There is nothing wrong with the parsing of the JSON -- in fact there is no problem at all.
consol.log limits the depth of what it is printing which is why you are seeing [object] in the output.
If you want to see the full output in node.js then just use the inspect utility like this;
console.log(util.inspect( yourobject, {depth:null} ));
and that will print the entire content.
Note that this is just an artifact of console.log printing it.

jQuery Datatables fnReloadAjax works but generates an alert

I am using the following code to reload the data in a jQuery datatable.
$(".unread-rows").click( function(e) {
e.preventDefault();
message_table.fnReloadAjax("/letters/ajax/inbox/1");
message_table.fnDraw();
$(this).addClass("active").siblings().removeClass("active");
});
It reloads the data fine but it also causes an alert to appear saying:
DataTables warning (table id = 'DataTables_Table_0'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.
Any ideas what might be causing this?
Barring any bugs in the fnRelaodAjax function :
Have you checked if your server returns valid json data ?
Have you checked if it returns an object with the following structure : {aaData: [...]}, or a structure that matches your sAjaxDataProp property ? (look for "sAjaxSource" and "sAjaxDataProp" in the doc page)

IE7 JSON Response: Object Expected.. Works in Chrome and FireFox

This is the last thing I have to do before I can send my beloved webapp into the wild, but of course IE7 is being difficult with me!!
I am using the JQuery Form plugin to upload data to my server. A servlet class will then run some operations with the file and shoot back some JSON to the client. As always, Chrome and Firefox handle the response like champs and give me the output I expect.
Internet Explorer 7 does not. I get an "Object Expected" error.... I have narrowed down my problem to a single function. I have made an educated guess that IE7 is not handling the response properly, but I really don't know. Here is the actual code that causes problems:
function uploadScript() {
$("#uploadScript").ajaxSubmit({
beforeSend: function() {
$("#uploadScript").attr("disabled", true);
},
dataType: "json",
cache: false,
success: function(response, status, xhr) {
if(response != undefined) {
commandArray = ([]).concat(response.command);
paramsArray = ([]).concat(response.params);
IDArray = ([]).concat(response.id);
commandID = response.commandID;
updateScriptView();
}
}
})
}
I have already tried explicitly setting the response header content type to 'application/json' to no avail. I have even read somewhere that such a header will even cause IE to bug out, so that front has certainly been confusing.
Perhaps it is the JSON syntax? Nope! I checked it, double checked it, then ran it through JSONLint just to be sure.
Any ideas on what I'm doing wrong?
EDIT: The JSON response literally is this:
{ "command" : ["sequential","wait","tune","endsequential"],"params" : [["5"],["00:00:03"],["202","RA29B[*]"],["100000"]],"id" : [100000,100002,100003,100001],"commandID" : 100004}
Eye-friendly is this:
{
"command": [
"sequential",
"wait",
"tune",
"endsequential"
],
"params": [
[
"5"
],
[
"00:00:03"
],
[
"202",
"RA29B[*]"
],
[
"100000"
]
],
"id": [
100000,
100002,
100003,
100001
],
"commandID": 100004
}
ANSWERED! Apparently, my $.attr() call in the beforeSend option of the ajaxSubmit() was causing problems in IE7. I do not know why this is the case, and my Googling yielded no results (Gotta Google the right question to get the right answer). Anyway, removing this code block solved my issue. I appreciate ALL the help that was given to me. Thanks guys!
Looks like you're using malsup plugin. If that's the case then the git repo has some known issues with this plugin:
https://github.com/malsup/form/issues
Check that your issue is not one already reported. Also check you jQuery version
this is the one for you: https://github.com/malsup/form/issues/179

Multiple datatables per page

I have multiple data tables per page, ranging from 4 to 8 ish.
All the tables have different settings. All the data is gotten via sAjaxSource (a javascript array).
My question boils down to:
Solution 1)
Should I have one seperate URL for each table? This seems to work, but means a full page load takes a lot longer.
Solution 2)
Have one same link for all the tables (and have seperate array name), so its only 1 download.
My questions are as follows:
Is there any recommmended solution for multiple data tables per page, that's best practice in terms of 1 or multiple links to get the javascript arrays.
If you provide the same ajax link to multiple datatables the browser seems to download them once per table instead of 1 time for all tables. Is this per "design" or a fault in my code?
Side note: I have checked http://www.datatables.net/examples/basic_init/multiple_tables.html and search the documentation but did not learn anything about the above questions.
In the case you described above, I would not rely on browser cashing, instead I would get data with my own single Ajax request. Store it in a local variable and for different tables use 'aaData' option.
var mydata;
$.ready(function(){
$.get("source/file.php", function(data){
mydata = data;
$('#table1').dataTable({ "aaData": mydata[0] });
$('#table1').dataTable({ "aaData": mydata[1] });
}, 'json');
});
but in the end solution depends on your needs, maybe you'll need lots of data, maybe it ll require paging and would be better off with multiple 'source' files with differed loading options etc.
The fact that the browser download the file only the first time when you provide the same link is, I think, due to the browser caching capabilities and has nothing to do with DataTables or your code. The browser put the content in its cache the first time and then serves it from there.
You can use this fact to your advantage by using the sAjaxDataProp option. I'm thinking something along these lines :
$('#table1').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "table1"
} );
$('#table2').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "table2"
} );
[ ... ]
$('#tableN').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "tableN"
} );
This will tell DataTable to look for a specific javascript array in the loaded content. Obviously, the data.txt file must contain the declaration of each table.
If you want to be sure that the browser do only one request, you could also load the data by an other means, a jQuery AJAX function for example, and then initialize the DataTables with an javascript array :
$('#table1').dataTable( { "aaData": array1 } );
$('#table2').dataTable( { "aaData": array2 } );
$('#tableN').dataTable( { "aaData": arrayN } );
I hope this will help :)

ExtJS: autoLoad does not work in IE

Using ExtJS 2.2.1, I've got a container element which is supposed to load a piece of HTML from the server using:
autoLoad: { url: 'someurl' }
This works fine in Firefox, but for IE7 this results in a syntax error in ext-all-debug.js at line 7170:
this.decode = function(json){
return eval("(" + json + ')');
};
I fixed this by turning that function into this:
this.decode = function(json){
return eval('(function(){ return json; })()');
};
Then the autoLoad works well in both browsers, but then there's some odd bugs and besides, you really don't want to fix this in the ExtJS library as it will be unmaintainable (especially in the minified ext-all.js which is like half a megabye of Javascript on a single line).
I haven't been able to find a lot about this bug.
Variations that I've tried:
// With <script> tags around all the HTML
autoLoad: { url: 'someurl', scripts: true }
// With <script> tags around all the HTML
autoLoad: { url: 'someurl', scripts: false }
And visa versa without the <script> tags. There isn't any Javascript in the HTML either, but it should be possible, because eventually we will use Javascript inside the returned HTML.
The problem isn't in the HTML because even with the simplest possible HTML, the error is the same.
UPDATE - Response to donovan:
The simplest case where this is used is this one:
changeRolesForm = new Ext.Panel({
height: 600,
items: [{ autoScroll: true, autoLoad: WMS.Routing.Route("GetRolesList", "User") + '?userID=' + id}]
});
There is no datastore involved here. The response-type is also text\html, not json, so that can't be confusing it either. And as said, it's working just fine in Firefox, and in Firefox, it also executes the same eval function, but without the error. So it's not like Firefox follows a different path of execution, it's the same, but without the error on eval.
Check your JSON. FF allow trailing commas in JSON objects while IE does not. e.g.
{foo:'bar',baz:'boz',}
would work in FF but in IE it would throw a syntax error. In order for there to not be a syntax error the JSON would need to be:
{foo:'bar',baz:'boz'}
I located the source of the problem and it was indeed not with ExtJS. There was a section in the application that listened to the Ext.Ajax 'requestcomplete' event and tried decoding the response.responseText to json, even if the response was HTML (which it only is in one or two cases). IE was not amused by this.
If you're autoLoad'ing into a Panel or Element then a JSON decode shouldn't even be involved in the process. UpdateManager just defers to Ext.Element.update(..) which takes a string of html.
The only reason I can think that your response would be parsed as JSON is if you were using a JSONStore to request it - what are you using?
You should be able to do something simple like this:
var panel = new Ext.Panel({
autoLoad: 'someurl' // this is the short form, you can still use the object config
});
OR
var element = Ext.get('element id').update({
url: 'someurl'
});
Response to Update:
That looks correct as long as something weird isn't happening with the WMS.Routing.Route(...) method. I'm actually currently working on an ExtJS application myself so I was able to quickly test some different server responses and couldn't reproduce your problem. I've also relooked at the ExtJS 2.2.1 sources and still see nothing in the related Element update and UpdateManager that would make the call to Ext.util.JSON.decode(...) that you're seeing.
I'm imagining that its from an unrelated AJAX request in another part of your application. If you're not already, I would use firebug / firebug lite to help debug this - specifically try to get a stack trace to make sure the source of your problem really is this autoLoad.
I had the same problem, excuse my english, i'm from Mejico, i hope I can help… my problem was triggered when I submit a Form to login, my PHP returns a JSON with the response in case of failure like this:
$respuesta = "{success: false, msgError: 'El usuario o contraseña son incorrectos'}";
but I wasn't send a resposne when it success, well when it has a true success, then the ExtJS it was trying to decode my JSON response, but there was nothing to decode, i guess that was, in my case again, the problem… I solved just sending back a response for the true succes, FF, Chrome, Safari, dont catch the problem, but Opera and IE8 does… I hope I help someone, goodbye
I don't know what the problem is, but I wanted to point out that your "fix" makes it simply return the json as a string instead of an eval'd object, so of course there is no error anymore -- you removed the functionality. It could just as simply be:
this.decode = function(json){
return json;
}
Generally speaking, random errors like this do not usually indicate a bug in Ext, especially not in functions used as commonly as Ext.decode. I would guess that either there is something in the JSON that IE does not like that other browsers ignore, or more likely, there is something unexpected going on in your app that is not obvious from your description. Have you tried inspecting your request log in Firebug to see what the JSON actually looks like? Have you tried getting the result of your Route call into a variable first to verify its contents before populating the panel? Also, try setting the "break on all errors" option in Firebug to true -- a lot of times when you get a random function from Ext at the top of your stack trace, the culprit is actually some application code that you weren't expecting.

Categories