Sending POST data through datatables ajax request - php

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.

Related

Datatables - sorting by and pagination

I'm fresh, but I'm learning with the help of people like you :). I need to do a table on my site that will display sorted data by type and pagination. I thought to use this solution: https://legacy.datatables.net/examples/data_sources/server_side.html
But honestly, I do not know how to do this. Can someone give an example along with html how to do it? Or suggest a different solution?
First of you need to import some of the necessary files:
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
CSS :
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
Then using the id attribute of the table you have created use the following code :
var table = $('#myTable').DataTable(); // this creates a table object of the DataTable class
// myTable is the id of the table you have created
table.clear().draw();
table.destroy();
$.ajax({
url: 'abc.php',
type: 'POST',
data: {value:value},//value you want to send to backend
dataType: 'json',
success:function(result){
$('#myTable').DataTable( {
"pageLength": 10, // does pagination providing 10 records per page
"destroy": true,
"language": {
"zeroRecords": "No Data Found",
"infoEmpty": "No Data Found",
},
"ajax": "objects.txt",
// Data from backend is sent to objects.txt file in JSON format
"columns": [
{ "data": "Key value from backend for 1st column in table" },
{ "data": "Key value from backend for 2nd column in table" },
{ "data": "Key value from backend for 3rd column in table" },
{ "data": "Key value from backend for 4th column in table"},
{ "data": "Key value from backend for 5th column in table" },
{ "data": "Key value from backend for 6th column in table" }
]
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
You could import more datatable javascripts that can provide more functionality such as conversion of table data to pdf or export as an excel file using button datatable javascripts. You can find more related information here : https://cdn.datatables.net/

DataTables warning: table id={id} - Invalid JSON response

I know above error is explain here " LINK "
All is working fine in my local-host thats no error popup , nothing in my local-host.
But on my online server i am getting above link error : i am not getting what and where is wrong as when i refresh my page after error then i get data properly .
It works for some time and then again start giving me error and again after refresh of page , error is not seen and my table list all data properly .
I check my all MySQL query on my server its working properly and fine.
var oTableL1 = $('#table1').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "includes/db/list_db.php",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "more_data", "value": "tablequeryone" } );
// aoData : passing parameter in my list_db.php where
i have used if else-if code for resp. which is working fine
in my local-host, also on server after refresh
}
});
var oTableL2 = $('#table2').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "includes/db/list_db.php",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "more_data", "value": "tablequerytwo" } );
}
});
var oTableL3 = $('#table3').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "includes/db/list_db.php",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "more_data", "value": "tablequerythree } );
}
});
ONLINE SERVER : IF I REFRESH MY PAGE then some time it get my data properly but some time its show me error , but after refresh of page it show me data properly without any error .. not getting what wrong.
same thing is happening for search and pagination and records list .
Since you are getting output on random refresh it has to do with the data table initialization and assignment of data. There are multiple scenarios that can lead to above error;
If data is being assigned to grid prior to element is registered in DOM
Data table is being initialized multiple times when its already available in the DOM
Solution; Clear the table and reassign the data.
Data mist match (in short grid contains columns; Col1, Col2, Col3 while table array is
not of same length)

How to retrieve edited data from extjs property grid?

I have this simple code:
var store = {
"(name)": "My Object",
"Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),
"Available": false,
"Version": 0.01,
"Description": "A test object"
}
Ext.create('Ext.grid.property.Grid', {
title: 'Properties Grid',
width: 300,
renderTo: Ext.getBody(),
source: store,
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
items: ['->', {
//iconCls: 'icon-save',
text: 'Sync',
scope: this,
// handler: this.onSync
}]
}]
});
The panel looks like this:
My app uses similar grid, the only difference is that the store variable is created dynamically (but has similar structure) and I also have a sync button that should save any changes to the grid's value field.
As of now, value field can be edited but not saved anywhere of course. I have been trying to add an event on sync button click, that would get all the rows from value and update the database.
Can anyone tell me step-by-step what to add in property.Grid's code, so that when I click sync
it would send all the values via AJAX to my php file, that would do the sync with database?
Thanks
Something like this should do the trick:
{
text: 'Sync',
handler: function() {
// get values
var gridvalues = this.up( 'propertygrid' ).getSource();
// send AJAX request
Ext.Ajax.request({
url: 'somephpurl...',
params: gridvalues
});
}
}
The docs, BTW, for these are as follows:
Get property grid values: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.grid.property.Grid-method-getSource
Create AJAX request: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Ajax-method-request

can't add data to jqGrid from php within json format

Hello StackOverFlow nation . I'm trying to add information to jqGrid , which is retrieved from MySQL database. I've two files => index.html and data.php (both in the same directory)
index.html source =>
<script type="text/javascript">
$(function(){
$("#jqGrid_tb").jqGrid({
url: "data.php",
datatype: "json",
sortable: true,
height: "auto",
colNames: ["Name","Surname","Birth Year","Famous Film"],
colModel: [
{name: "name", index: "name", width: "150"},
{name: "surname", index: "surname", width: "150"},
{name: "b_year", index: "year", width: "150"},
{name: "film", index: "film", width: "200"}
],
rowNum: 5,
rowList: [5,10,15],
viewrecords: true,
pager: $("#pager"),
caption: "Famous Actors",
}).navGrid("#pager");
});
</script>
<div id="grid">
<table id="jqGrid_tb"></table>
<div id="pager"></div>
</div>
data.php source =>
include ("JSON.php");
$json = new Services_JSON();
$con = new mysqli("host","user","pswd","db");
if (!$con->connect_errno){
if ($r = $con->query("SELECT * FROM actors")){
while ($row = $r->fetch_assoc()){
$info[] = array(
"name" => $row[name],
"surname" => $row[surname],
"b_year" => $row[b_year],
"film" => $row[film],
);
}
$r->free();
}
}
echo $json->encode($info);
if (isset($con)){
$con->close();
}
jqGrid is shown without any information in index.html file , also when opening data.php file information is successfully encoded into JSON format , whats wrong I can't understand . Please help , thanks ...
Your response format is wrong. You can go to jqGrid Demos page where you will find a sample for PHP/MySQL after expanding Loading Data and then choosing JSON Data.
The proper format of data should look like this:
{
"total": "1",
"page": "1",
"records": "2",
"rows": [
{ "name": "Robert", "surname": "De Niro", "b_year": "1943", "film": "Once Upon A Time In America" },
{ "name": "Al", "surname": "Pacino", "b_year":"1971", "film": "Scent Of A Woman"}
]
}
Where:
total --> total count of pages
page --> current page number
records --> total count of records
rows --> the rows of data
Also if you want rows to be objects, you need to disable repeatitems in jqGrid jsonReader options:
$("#jqGrid_tb").jqGrid({
...
jsonReader: { repeatitems: false }
});
It is also adviced for rows to have unique id for later reference.
You should include
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
as additional option of jqGrid is you don't want to change format of input data. Moreover you should specify which values should assign jqGrid as id attribute of the row. You can include additional id property as additional property of every returned item or you can add key: true property to the column (in colModel) which contains unique values. For example if you can guarantied that the values from "name" are already unique then you can include key: true property in definition of "name" column.
Additionally you can consider to use loadonce: true option of jqGrid. In the case the full data of the grid will be loaded at once and the sorting, paging and searching (filtering) of data will be implemented by jqGrid on the client side without needs to implement some additional code on the server side. You should don't use the option in case of large number of rows (many hundred or many thousand rows) in the grid.

DataTables with JSON, AJAX and PHP not displaying any data

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

Categories