PHP with DataTables gives an Invalid JSON response due to quotes - php

I encountered a problem fetching my data from my database and display it via DataTables. I found out that most of my data has single and double quotes and other special characters. I tried every escaping functions in PHP but it didn't work. addslashes only retrieves 59 data out of 40,000 data. So far, i have this code:
PHP:
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$table = '';
while($row = mysqli_fetch_array($query)) {
$table.= '{
"allotment_code":"'.$row['allotment_code'].'",
"activity":"'.$row['activity'].'",
"category_name":"'.addslashes($row['category_name']).'",
"description":"'.addslashes($row['description']).'"
},';
}
$table = substr($table,0, strlen($table) - 1);
echo '{"data":['.$table.']}';
**jQuery data tables:**
$(function() {
$('#dataTables-example').DataTable( {
"bLengthChange": false,
"pageLength": 50,
"bDeferRender": true,
"bProcessing": true,
"sPaginationType": "full_numbers",
"ajax": base_url('ajax/ajaxGetBOM.php'),
"columns":[
{mData: "allotment_code"},
{mData: "activity"},
{mData: "category_name"},
{mData: "description"}
],
contentType: 'application/json',
dataType: 'json'
});
})
function base_url(path) {
var url = 'https://192.168.3.254/'+path;
return url;
}
The error is like this:

Use json_encode() function to properly encode your response using JSON format.
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$data = array();
while($row = mysqli_fetch_array($query)) {
$data[] = array(
"allotment_code" => $row["allotment_code"],
"activity" => $row["activity"],
"category_name" => $row["category_name"],
"description" => $row["description"]
);
}
header("Content-type: application/json");
echo json_encode(array("data" => $data));

Related

PHP - Create a json file from mysql

I know my code below isn't the best way of doing what i'm trying to do here, but I need a way to remove just the double quotes from the key values only using PHP. I need to keep the double quotes inside the "src attribute" though!
Here is my PHP code:
$host = "localhost"; //Your database host server
$db = "root"; //Your database name
$user = "root"; //Your database user
$pass = "1234"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM playlist_builder";
$resultset = mysql_query($query, $connection);
$records = array();
$response = array(); //extra
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
$json = json_encode($records, JSON_PRETTY_PRINT);
$json = str_replace('\\', '', $json);
$json = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9_]*)":/','$1:',$json);
// $json = str_replace('"', "'", $json);
//NOTE: FOLDERS 'url' and 'file' SHOULD BE WRITABLE WITH PERMISSIONS - 777
//IN CASE 'url' FOLDER PLACED IN SERVER'S ROOT
//IF YOU'RE USING SOME FTP BROWSER CHANGE PERMISSIONS FOR 'url'
//FOLDER AND APPLY IT TO ALL ENCLOSED ITEMS
$data = 'var data = [{ tags: ';
$end = '}];';
$script = "// Call Slider function
$(window).load(function () {
$('#slideshow-slider').jSonSlider({
'loadallslides': false,
'auto': [true, '14000'],
'nextprev': false,
'circular': true,
'pagi': false,
'data': data
});
});";
file_put_contents('records.js', $data);
file_put_contents('records.js', $json, FILE_APPEND);
file_put_contents('records.js', $end, FILE_APPEND);
file_put_contents('records.js', $script, FILE_APPEND);
}
}
Here is my Output of my js file:
var data = [{ tags: [
{
id: "1",
volume: "volume1",
name: "a",
content: "<img src="../../../image1.jpg">",
css_animate: "fadeIn"
},
{
id: "2",
volume: "volume1",
name: "a",
content: "<img src="../../../image2.jpg">",
css_animate: "fadeIn"
},
{
id: "3",
volume: "volume1",
name: "a",
content: "<img src="../../../image3.jpg">",
css_animate: "fadeIn"
}
]}];
// Call Slider function
$(window).load(function () {
$('#slideshow-slider').jSonSlider({
'loadallslides': false,
'auto': [true, '14000'],
'nextprev': false,
'circular': true,
'pagi': false,
'data': data
});
});
Any help is really appreciated! :)
My recommendation would be to use Collection that comes with illuminate/support package. You can pass your associative array to the Collection's constructor, then map through it and return as json.
Example would be:
use Illuminate\Support\Collection;
$collection = new Collection($records);
$json = $collection->map(function(array $record) {
return [
id => $record['id'],
volume: $record['volume'],
name: $record['name'],
content: '<img src="../../../'.$record['image'].'">',
css_animate: "fadeIn"
];
})->toJson();
I understand you are converting a PHP array to JSON, and then converting that JSON to Javascript object. Why don't we let Javascript itself convert the JSON to a JS object? Like this:
// JSONify $records. We need the slashes for the
// string to work correctly in Javascript.
$jsonRecords = addslashes(json_encode($records));
// This is the JS file contents (using PHP's heredoc string syntax).
// The $jsonRecords string is inserted as part of that JSON string.
$fileContents = <<<DOC
var data = JSON.parse("[{\"tags\": $jsonRecords }]");
// Call Slider function
$(window).load(function () {
$('#slideshow-slider').jSonSlider({
'loadallslides': false,
'auto': [true, '14000'],
'nextprev': false,
'circular': true,
'pagi': false,
'data': data
});
});
DOC;
// Create a file and write to it once.
file_put_contents('records.js', $fileContents);
We convert $records to JSON and insert it inside a JSON string (var data), which is parsed by Javascript's JSON.parse function. Now we don't have any troubles with quotes.

Server Side datatables using PHP and Ajax

This is my DataTable code:
$('#open').DataTable( {
select: true,
"processing": true,
"sAjaxSource": "booked1.php",
"serverside": true,
"columns" :[ {
"data" : "name"
}, {
"data" : "date1"
}, {
"data" : "bookingtoken"
}, {
"data" : "insurance"
}]
} );
This is my ajax call :
$("#submit").on('click', function () {
$('#loadarModal').modal({backdrop: 'static', keyboard: false});
var date = $("#date").val();
//alert(date);
if (date == '') {
$("#dateText").show();
$("#dateText").html("Please select date");
$("#loadarModal").modal('hide');
} else {
$("#dateText").hide();
//alert("can processd");
var data = $("#form").serialize();
$.ajax({
type: 'POST',
url: 'booked1.php',
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
alert(response);
if(response==''){
}
$("#booking").html(response);
$("#loadarModal").modal('hide');
}
});
}
});
This is my PHP Script:
include 'd_b_con.php';
if(isset($_POST['date'])){
$date=$_POST['date'];
$query=mysqli_query($conn,"select date as date ,tokenno as tokenno ,inusrance as inusrance,bookingtoken as bookingtoken ,
fname as fname,lname as lname , status as status from at_booking where date='$date'");
$data=array();
while($row1=mysqli_fetch_array($query)){
$data[] = $row1;
$date1=$row1['date'];
$tokenno=$row1['tokenno'];
$bookingtoken=$row1['bookingtoken'];
$fname=$row1['fname'];
$lname=$row1['lname'];
$status=$row1['status'];
$insurance=$row1['inusrance'];
$name=$fname.' '.$lname;
echo '<tr>';
echo "<td>$name </td>";
echo "<td> $date1 </td>";
echo "<td>$bookingtoken </td>";
echo "<td>$insurance </td>";
echo '</tr>';
$result=array(
"name" => $name,
"date1" => $date,
"bookingtoken" => $bookingtoken,
"insurance" => $insurance
);
echo json_encode($result);
}
This is the first time I am using server side data tables.
I am getting error like "DataTables warning: table id=open - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"
Can anyone guide me how to use data tables server side for my code.
Try to change this code,
$result = [];
$result[]=array(
"name" => $name,
"date1" => $date,
"bookingtoken" => $bookingtoken,
"insurance" => $insurance
);
echo json_encode($result);
die;
Once check in network->xhr whether you are getting any response or not.
You really overcomplicate this. You should never echo out the actual <tr><td>.. markup, this is why you get the warning. And use mysqli_fetch_assoc instead :
$data = array();
while( $row1 = mysqli_fetch_assoc($query) ){
$row1['name'] = $row1['fname'].' '.$row1['lname'];
$row1['date1'] = $row1['date']; //??
$data[] = $row1;
}
echo json_encode($data);
Update. You will probably need to use
echo json_encode( array('data' => $data) );
If you not set dataSrc to ''.

how to add row as html to BootStrap Plugin DataTable?

Is there a way to add row as html to datatable? I understand that the suggested way of doing it is this:
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
counter++;
} );
But I have a complex JSON input and I want to pre process it in PHP. Is it doable or even possible?
EDIT:
So instead of doing the code above:
t.row.add(resultfromphpserverwithalltherows);
UPDATE:
JSON output
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
and sometimes:
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
So I can't really define the columns because the JSON output is dynamic and that's why I want to preprocess it in PHP first.
No matter how you approach this, there's going to be some significant data-formatting required.
Best approach for what you're asking: use DataTables server-side tools.
It requires including some additional components, but will simplify the javascript down to:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
...with a little tweaking, you can simplify that further:
$(function(){
var dt = new dataTableAuto();
dt.load();
});
function dataTableAuto() {
this.params = {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
};
this.load = function() {
$('#example').DataTable( this.params );
}
}
php ajax server to send raw JSON as a single row
Simply send an ajax request to php which includes the counter, then respond with a json array matching what you want to build.
Javascript snippet
counter = 0;
$.ajax({
url: '[your url]',
type: 'post',
data: {"counter":counter},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.row.add(JSON.parse(response)).draw( false );
counter++;
},
});
php Snippet
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;
for( $i = 0; $i < $totalRows; $i++) {
$result[] = $counter .".". $i;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
DataTables pure AJAX approach
javascript
$(function(){
t = $('#example');
$.ajax({
url: '[your url]',
type: 'post',
data: {"classID":12},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.DataTable( JSON.parse(response) );
},
});
});
php
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);
$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
$entry = new stdClass();
$entry->title = $colName;
$result['columns'][] = $entry;
}
$result = // some query [ex: get rows by class id]
foreach( $result as $row) {
$thisRow = array();
foreach ( $cols as $colName ) {
$thisRow[] = $row['$colName']
}
$result['data'][] = $thisRow;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
This should produce an object similar to:
{
data: [
['Joseph Taylor', '22', '90']
],
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Score" }
]
}

ExtJS 5.1, grid load data from database with PHP

I am doing an online course of Ext JS 5.1 and in this exercise I have a service.php file which connects to database and returns JSON Data. I try to show this data but it never gets displayed (doesn't show any error message in firebug) and I can`t find what is the problem with the code.
This is the code of the store:
var storeUsuario = Ext.create('Ext.data.Store', {
model : 'js.clase.Usuario',
proxy: {
type: 'rest',
url: 'service.php?method=getUsuarios',
reader: {
type: 'json',
}
},
autoLoad: true
});
This is the code of the grid:
Ext.create('Ext.grid.Panel', {
renderTo: Ext.getBody(),
store: storeUsuario,
width: 600,
height: 400,
title: 'Grid Usuarios',
columns: [
     {
text: 'id',
dataIndex: 'id'
},{
            text: 'nombre',
            width: 100,
            dataIndex: 'nombre'          
},{
        text: 'apellidos',
        dataIndex: 'apellidos'
},{
        text: 'email',
        dataIndex: 'email'
},{
        text: 'nacionalidad',
        dataIndex: 'nacionalidad'
},{
        text: 'rutaAvatar',
        dataIndex: 'rutaAvatar'
}
]
});
and the service.php method:
<?php
header('Content-Type: text/html; charset=utf-8');
$conexion = mysql_connect("127.0.0.1", "root", "");
mysql_select_db("usertest", $conexion);
$method = $_GET['method'];
switch($method) {
case "getUsuarios":
$query = "SELECT * FROM Usuario ORDER BY id ASC";
$result = mysql_query($query, $conexion) or die(mysql_error());
$numRows = mysql_num_rows($result);
$usuarios = array();
if ($numRows > 0) {
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$usuarios[$i] = $row;
$i++;
}
}
$usuariosJSON = json_encode($usuarios);
echo $usuariosJSON;
break;
}
?>
Your PHP code doesn't return a valid JSon.
See this fiddle works correctly: https://fiddle.sencha.com/#fiddle/q9k
According to this post you should specify the header.
And I suggest you to return a "hand formed" json like this:
$data = /** whatever you're serializing **/;
$data_length = /* the length of the result according to the request response */;
header('Cache-Control: no-cache, must-revalidate'); // just to be sure
header('Content-Type: application/json');
echo "{ \"success\": true, \"total\": $data_length, \"records\": " . json_encode($data) . " }";
The json data could need []...
echo "{ \"success\": true, \"total\": $data_length, \"records\": [ " . json_encode($data) . " ] }";

jQuery AJAX call to a database query

I have an AJAX function as so:
function admin_check_fn(type)
{
//$("#notice_div").show();
//var allform = $('form#all').serialize();
$.ajax({
type: "POST",
//async: false,
url: "<?php bloginfo('template_url'); ?>/profile/adminquery_check.php",
data: { type: type },
//data: 'code='+code+'&userid='+userid,
dataType: "json",
//dataType: "html",
success: function(result){
var allresult = result.res
$('#result').html( allresult );
alert(allresult);
//$("#notice_div").hide();
}
})
}
And server-side:
$queryy="SELECT * FROM wp_users";
$name = array();
$resultt=mysql_query($queryy) or die(mysql_error()); ?>
<?php while($rowss=mysql_fetch_array($resultt)){
$name = $rowss['display_name'];
}
echo json_encode( array(
"res" => array($rowss['display_name']),
"fvdfvv" => "sdfsd"
)
);
Basically for some reason it is not displaying all of the returned values from the query to the users table in the database. It works when I query another table with just one entry in it, so im thinking it could be something to do with the fact there is an array it is not parsing correctly?
Just wondered if anyone else has came accross this problem?
Thanks
Your ajax success is treating the returned data as html but it is json.
var allresult = result.res
/* assumes allResult is html and can be inserted in DOM*/
$('#result').html( allresult );
You need to parse the json to create the html, or return html from server
Also php loop:
$name = $rowss['display_name'];
Should be more like:
$name[] = $rowss['display_name'];
You always overwrite the name:
<?php while($rowss=mysql_fetch_array($resultt)) {
$name = $rowss['display_name'];
}
But this part is not within your loop:
"res" => array($rowss['display_name']),
Therefore you only get one result (the last one).
Smamatti has a good point.
To fix this:
<?php
$query = "SELECT * FROM wp_users";
$names = array();
$result = mysql_query($query) or die(mysql_error());
while( $rows = mysql_fetch_array( $result ) ){
$names[] = $rows['display_name'];
}
echo json_encode( array(
"res" => $names,
"fvdfvv" => "sdfsd"
)
);

Categories