I'm trying to make a simple ajax call in datatables that is reliant on a post array of IDs from a previous page's form. I am getting the error :
Invalid JSON Response
which tells me that my returned json array is probably empty or something and I have a feeling it has to do with the POST data not being sent to my php/sql external script on which ajax is requesting the data from.
I'm not sure how to test it as I don't know how to include the $_POST data in the URL to my external php page to outright trigger the script.
Heres my current datatables init and php from the results page:
<?php
include_once('../functions.php');
sec_session_start();
print_r($_POST['post_id']); <-- making sure the post data made it this far
?>
<script type="text/javascript">
$(document).ready(function() {
var compTable = $('#compTab').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "baddebt_ext_sql.php",
"type": "POST",
"dataType": 'json',
"data": {"post_id": $_POST['post_id']}
},
"Columns": [
{ "data": "provider_num" },
{ "data": "provider_name"},
{ "data": "261_total_bed_debts", "sClass": "rightAlign" },
{ "data": "271_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "281_non_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "1_cost_to_charge_ratio", "sClass": "rightAlign" },
{ "data": "291_cost_of_non_mcr_bad_debts", "sClass": "rightAlign" }
],
"scrollY": "600px",
"scrollCollapse": true,
"paging": false,
"order": [[ 2, "desc" ]],
"oLanguage": { "sSearch": "Filter All Fields By:" },
"Dom": '<"clear">lfrtipT',
"TableTools": {
"sSwfPath" : "../php/tabletools/swf/copy_csv_xls_pdf.swf" }
});
and here is my SQL:
<?php
include_once('../link_costreport_2013.php');
if(isset($_POST['post_id'])){
$in = $_POST['post_id']; <-- THIS IS WHERE THE POST DATA IS SUPPOSED TO BE RECEIVED
}
$data = array();
foreach ($in as $id){
$query = $link->prepare("SELECT id,provider_num, provider_name, 261_total_bed_debts, 271_medicare_bad_debts, 281_non_medicare_bad_debts, 1_cost_to_charge_ratio, 291_cost_of_non_mcr_bad_debts
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
$results['261_total_bed_debts'] = "\$".number_format($results['261_total_bed_debts']);
$results['271_medicare_bad_debts'] = "\$".number_format($results['271_medicare_bad_debts']);
$results['281_non_medicare_bad_debts'] = "\$".number_format($results['281_non_medicare_bad_debts']);
$results['291_cost_of_non_mcr_bad_debts'] = "\$".number_format($results['291_cost_of_non_mcr_bad_debts']);
$results['provider_name'] = "<a id='".$results['id']."' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
$data[] = $results;
}
echo json_encode($data);
If anyone knows how I can get my json array from this script without utilizing the previous pages $_POST data it is supposed to send, then I will gladly post it as well.
Basically I'm just wondering if there are any steps I am missing when it comes to feeding this array of IDs through my datatables ajax query and into the second page's sql. ( an example of the post_id array is like this:
Array ( [0] => 299 [1] => 1555 [2] => 3539 ))
Diagnosing this problem is pretty easy. Simply right mouse click and "inspect element" then choose the Network tab. Toggle the transaction as you would in your interface. You'll see a new network transaction in the network tab.
Click on that new network transaction -- it should have the address that you're defining in the ajax call. The headers will show the variables you sent via post, response will show what the server returned.
The error is indicating that your response will fail if you paste the payload into jslint.com and evaluate it. What the cause of that failure is will require more details than you've provided.
In the ajax example you use, "data" is the data that's being sent to the server. To send a large amount of data in that post, I'd enclose your inputs in a form tag, then do a $.serialize or $.serializeArray on that form. You can then send that serialized data over as a variable via the data attribute, where it will be posted to your server. From there, just deal with the resulting post variables via PHP.
Please do update your code to use 1.10 API variables. Support for the old ones will be deprecated in the future versions.
I've been trying to get DataTables to work with my existing Ajax search function - which works by itself.
I have the following code:
$('#SearchResults').dataTable({
"bProcessing": true,
"bServerSide": true,
"bRetrieve": true,
"sAjaxSource": "process.php?action=searchArtifact",
"fnServerData": function (sSource, aoData, fnCallback){
aoData.push({
"name": "searchName",
"value": $('#ArtifactSearch').attr('value')
});
$.ajax({
"dataType": "json",
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The PHP is returning a valid JSON object (using JSON_FORCE_OBJECT):
{"0":{"ARTIFACT_ID":"4E2FE3BCE356C","ARTIFACT_NAME":"123","ARTIFACT_TYPE":"UI","ARTIFACT_LABEL":"Test_Int_EAS_123","ARTIFACT_LOCATION":"Int","ARTIFACT_DOMAIN":"ABC","ARTIFACT_AUTHOR":null,"REGISTERED_EMAIL":"test#test.com","REGISTERED_DATE":"27-07-2011","REGISTERED_TIME":"11:09:00"}
I can see this all fine in FireBug, but my empty table is not being populated with this data.
Any ideas?
#Kyle: Errr - thats it. I guess I don't have one? This is my first attempt (struggle) with DataTables and I'm just copying from the documentation: http://www.datatables.net/usage/callbacks#fnServerData
#MarcB: Added that - but still no data displayed. Thanks for the help
I was having a similar problem. Turns out I wasn't forming the JSON response properly. This worked for me:
<?php
$arr = array ('aaData' => array(
array('3','35','4', '$14,500', '$15,200','$16,900','5','1'),
array('1','16','4', '$14,200', '$15,100','$14,900','Running','1'),
array('5','25','4', '$14,500', '$15,600','$16,900','Not Running','1')
)
);
echo json_encode($arr);
?>
This plugin expects the returned JSON object to be an object, with a property which is an array of arrays. This property should be called 'aaData'. You are not returning an object; you are just returning the array.
Check out this json resource example from DataTables.net: http://datatables.net/examples/examples_support/json_source.txt. Notice that you are returning json with brackets as compared to the example's braces.
you can remove the $.ajax part, instead you can use the $.getJSON method.
You can also add the following to avoid adding an extra object like "aaData":
"sAjaxDataProp": ''
What are you setting sEcho to?
Your JSON should have this structure:
{
"sEcho": 'refer to "sEcho" in $_GET or $_POST; don't forget to sanitize',
"iTotalRecords": 'for pagination',
"iTotalDisplayRecords": 'number displayed',
"aaData" => { /* your data here */ }
}
This is a few years late but might help someone. :)
DataTable cannot render null values. See defaultContent to set content when data return is null.
See link: https://datatables.net/reference/option/columns.defaultContent
For legacy dataTables, see http://legacy.datatables.net/ref and search for sDefaultContent
I'm trying to create a jqgrid, but the table is empty. The table renders, but the data doesn't show.
The data I'm getting back from the php call is:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}
The javascript configuration looks like so:
$("#"+tableId).jqGrid ({
url:'getAwards.php?id='+classId,
dataType : 'json',
mtype:'POST',
colNames:['Id','Badge','Name','Description',''],
colModel : [
{name:'awardId', width:30, sortable:true, align:'center'},
{name:'badge', width:40, sortable:false, align:'center'},
{name:'name', width:180, sortable:true, align:'left'},
{name:'description', width:380, sortable:true, align:'left'},
{name:'selected', width:0, sortable:false, align:'center'}
],
sortname: "awardId",
sortorder: "asc",
pager: $('#'+tableId+'_pager'),
rowNum:15,
rowList:[15,30,50],
caption: 'Awards',
viewrecords:true,
imgpath: 'scripts/jqGrid/themes/green/images',
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id",
userdata: "userdata",
subgrid: {root:"rows", repeatitems: true, cell:"cell" }
},
width: 700,
height: 200
});
The HTML looks like:
<table class="awardsList" id="awardsList2" class="scroll" name="awardsList" />
<div id="awardsList2_pager" class="scroll"></div>
I'm not sure that I needed to define jsonReader, since I've tried to keep to the default. If the php code will help, I can post it too.
I got it to work!
The dataType field should be datatype. It's case sensitive.
The problem also occures when you include script jquery.jqGrid.min.js before then grid.locale-en.js. Check this if there are any problems with controller's method call.
I experienced the same problem when migrating from jqGrid 3.6 to jqGrid 3.7.2. The problem was my JSON was not properly double-quoted (as required by JSON spec). jqGrid 3.6 tolerated my invalid JSON but jqGrid 3.7 is stricter.
Refer here: http://simonwillison.net/2006/Oct/11/json/
Invalid:
{
page:"1",
total:1,
records:"10",
rows:[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}
Valid:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}
I also got it to work: datatype is the correct spelling -- it's shown that way in the example but it is inconsistent with everything else in the library so it was easy to get wrong
I'm getting very tired chasing this sparse documentation around and I really feel like JSON, which is right and proper to be using in JavaScript, has really been given short coverage in favor of XML. Python and JavaScript together, through JSON, is a really strong combination, but it's a constant struggle with this particular library.
Anyone with an alternative that:
1> Properly supports jQuery UI themes (including rounded corners!) (http://datatables.net has much nicer support for themes)
2> Allows resizing of columns (http://datatables.net doesn't support this out of the box)
3> Allows sub-grids (http://datatables.net lets you do whatever you want here, through an event)
please let me know. I'm spending more time on this one part of my interface than on the whole rest of it combined and it's all the time spent searching for working examples and "trying things" which is just getting annoying.
S
This might be a older post but I will post my success just to help others.
Your JSON needs to be in this format:
{
"rows": [
{
"id": 1,
"cell": [
1,
"lname",
"fname",
"mi",
phone,
"cell1",
"cell2",
"address",
"email"
]
},
{
"id": 2,
"cell": [
2,
"lname",
"fname",
"mi",
phone,
"cell1",
"cell2",
"address",
"email"
]
}
]
}
and I wrote this model in Zend so you can use it if you feel like it. Manipulate it how you want.
public function fetchall ($sid, $sord)
{
$select = $this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->join('Subdiv', 'Subdiv.SID = Contacts.SID', array("RepLastName" => "LastName",
"Subdivision" => "Subdivision",
"RepFirstName" => "FirstName"))
->order($sid . " ". $sord);
$resultset = $this->getDbTable()->fetchAll($select);
$i=0;
foreach ($resultset as $row) {
$entry = new Application_Model_Contacts();
$entry->setId($row->id);
$entry->setLastName($row->LastName);
$entry->setFirstName1($row->FirstName1);
$entry->setFirstName2($row->FirstName2);
$entry->setHomePhone($row->HomePhone);
$entry->setCell1($row->Cell1);
$entry->setCell2($row->Cell2);
$entry->setAddress($row->Address);
$entry->setSubdivision($row->Subdivision);
$entry->setRepName($row->RepFirstName . " " . $row->RepLastName);
$entry->setEmail1($row->Email1);
$entry->setEmail2($row->Email2);
$response['rows'][$i]['id'] = $entry->getId(); //id
$response['rows'][$i]['cell'] = array (
$entry->getId(),
$entry->getLastName(),
$entry->getFirstName1(),
$entry->getFirstName2(),
$entry->getHomePhone(),
$entry->getCell1(),
$entry->getCell2(),
$entry->getAddress(),
$entry->getSubdivision(),
$entry->getRepName(),
$entry->getEmail1(),
$entry->getEmail2()
);
$i++;
}
return $response;
}
Guys just want to help you in this. I got following worked:
JSON
var mydata1 = { "page": "1", "total": 1, "records": "4","rows": [{ "id": 1, "cell": ["1", "cell11", "values1" ] },
{ "id": 2, "cell": ["2", "cell21", "values1"] },
{ "id": 3, "cell": ["3", "cell21", "values1"] },
{ "id": 4, "cell": ["4", "cell21", "values1"] }
]};
//Mark below important line. datatype "jsonstring" worked for me instead of "json".
datatype: "jsonstring",
contentType: "application/json; charset=utf-8",
datastr: mydata1,
colNames: ['Id1', 'Name1', 'Values1'],
colModel: [
{ name: 'id1', index: 'id1', width: 55 },
{ name: 'name1', index: 'name1', width: 80, align: 'right', sorttype: 'string' },
{ name: 'values1', index: 'values1', width: 80, align: 'right', sorttype: 'string'}],
Regards,
In my case, the problem was caused by the following line of PHP code (which was taken from jqGrid demo):
$responce->page = $page;
What is wrong here is that: I am accessing property page of object $responce without creating it first. This caused Apache to display the following error message:
Strict Standards: Creating default object from empty value in /home/mariusz/public_html/rezerwacja/apps/frontend/modules/service/actions/actions.class.php on line 35
And finally the error message used to be send to json reader within the script.
I fixed the problem by creating empty object:
$responce = new stdClass();
I don't think your ID is the correct type, I think it should be an int.
For the given json you really don't need the jsonreader settings. What you have listed is the defaults anyway, plus you don't have a subgrid in your json.
Try this:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":1 ,"cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":2,"cell":["2","image","Link Badge","When you are invested as a Scout, you maybe eligible to receive a Link Badge. (See page 45)","0"]},
{"id":3,"cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":4,"cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":5,"cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":6,"cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":7,"cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":8,"cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":9,"cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":10,"cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}
I was working with WAMP 2.4, I was being crazy with this problem, I tried lot of things, like install previous versions of PHP and like 5.2, een I tried in Windows XP, and lots of jqGrid options.
Well thank to Oleg finally and Mariusz I find the only line:
$responce = new stdClass();
Before the use of $responce could solve all, and now my grid is works Great!!!
Thanks my friends.