jQuery Datatables fnReloadAjax works but generates an alert - javascript

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)

Related

Running JS doesn't work on page load, but otherwise does

I'm fetching some JSON data to an HTML table using AJAX and jQuery.
The script is generating table rows with table data elements and is working properly.
I need to write another script which will count the number of table rows.
Logically I went with:
let rows = $('table tr').length
console.log(rows)
Running this on page load (e. g. $(document).ready) outputs a length of 0 to the console.
However, running it on any other event (e. g. click) works and outputs the correct length.
To my understanding, the browser runs the counting script before any of the table rows are loaded. Why does this happen? It appears later in the code than the table generating script.
How do I make it work properly on page load? Cheers.
What Matthew Herbst said, is totally right. Although since you are using jQuery, and according to the documentation on http://api.jquery.com/jquery.ajax/ I would suggest that you use the .done function (or alternativelly the success callback).
Examples :
Done method :
$.ajax({
url: "http://example.com/getRows.php",
})
.done(function( data ) {
// data received
doWhateverHere();
});
Success callback :
$.ajax({
url:"http://example.com/getRows.php",
success:function(data) {
// data received
doWhateverHere();
}
});

Datatable Invalid JSON response

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.

$('body').html() gave blank content from response data that come from $jQuery.post in Firefox

I got this javascript code in a JSP:
$('#myForm').submit(function(event) {
event.preventDefault();
var act = $('#myForm').attr('action') + '&act=' + $('#submitBtn').val();
var dataStr = $("#myForm").serialize();
$.post(act, dataStr, function(data, status) {
$('body').html(data);
});
return false;
});
The facts:
I'm using jquery v1.3.x (and I can't replace with newer version because of company policy).
The jsp is in a pop-up window.
There is a submit button with id=submitBtn
When the submit button is clicked, it will execute above code and send the data into struts action.
The action url:
someAction.do?someParam=blabla&someNo=213354345&mode=POP&act=Update Your Data
(note: I had replaced some sensitive data, but the argument pattern is same)
The problem is at this line:
$('body').html(data);
It produces Error: NS_ERROR_FAILURE: Failure in error console. I heard it's related with cross domain request, but my application is at localhost, how could it happened?
In IE 8, it successfully replaced the current page content with the data value (which is html string). But in firefox (v22), it gave blank page, I checked with right click -> View Source, it's really empty. Then I checked with firebug, the response data indeed contains the result html page string. If I debug with alert(data); before the $('body').html() call, it also show the html string.
So the $.post() function successfully returns the response data but it seems the $('body').html() function failed to render the data.
So what is actually happened? I'm really have no clue.
What is the solution for this?
UPDATE:
I checked the error console, I got this error after submitted the page:
Error: NS_ERROR_FAILURE: Failure
Source File: http://localhost:8080/myapp/script/jquery.js
Line: 19
UPDATE 2:
I debug the java code, I found out that the input html tag in the JSP that has indexed array name like this:
myItem[0].name
myItem[1].name
...
were not successfully submitted to the ActionForm class. I investigated the source of problem might come from a 3rd party javascript library.
try something like this
$.post(act, dataStr, function(data) {
document.body.innerHTML = data;
});

Incorrect JSON data format

I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.

jQuery jqGrid Show message when an edit row is complete

I am following this tutorial here http://www.trirand.com/blog/jqgrid/jqgrid.html in
LiveDataManipulation->EditRow
My grid receive data from script a.php. After the user can modify this data by the jqGrid.
jqGrid after the modification data will send data to script B.php that update my database and return a message of response like "all goes well".
I want that this response is alerted or showed to user somewhere on the page.
Reading the tutorial and here http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing I think that I've to use afterSubmit option, but I haven't understood how print on the edit panel the result.
I have written:
$("#editImpresa").click(function(){
var gr = jQuery("#tabImprese").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#tabImprese").jqGrid('editGridRow',gr,{
height:690,
width:500,
closeAfterEdit : true,
reloadAfterSubmit:false,
afterSubmit: function(response,postdata){
if(response.responseText=="ok")
success=true;
else success = false;
return [success,response.responseText]
}
});
How can I do it?
Thanks.
First of all the option closeAfterEdit:true follows to closing of the edit form after the successful server response. You should change the setting to the default value closeAfterEdit:false to be able to show anything.
Next I would recommend you to use navigator toolbar instead of creating a button after outside of the grid. In the case you can use
var grid = jQuery("#tabImprese");
grid.jqGrid('navGrid','#pager', {add:false,del:false,search:false}, prmEdit);
One more good option is to use ondblClickRow event handler
ondblClickRow: function(rowid) {
$(this).jqGrid('editGridRow',rowid,prmEdit);
}
(see here) or both ways at the same time.
In any way you have to define the options of editGridRow method (the prmEdit). It's important to know that afterSubmit will be called only if the server response not contains error HTTP status code. So you should use errorTextFormat to decode the error server response. The afterSubmit event handler you can use to display status message.
In the demo I used only errorTextFormat to demonstrate both displaying of the status and error message:
The status message goes away in 3 seconds:
The corresponding demo you will find here.
In real example you will of cause place the code writing status message inside of afterSubmit event handler and the code which returns the error message inside of errorTextFormat.

Categories