Set DataSource For jQuery DataTable to PHP JSON Encoded Array - php

I am using the below code to query MySql and return the results to an array. I have verified with a for each loop that this has my results as expected.
My last step of this process is to set this php array as the datasource for the jQuery Datatable? I have the below code but my DataTable is never created.
What am I missing?
<table id="example" class="display" width="100%"></table>
<?php
$con=mysqli_connect("site", "user", "psasswr=ord", "db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM test LIMIT 10";
$result = mysqli_query($con,$sql);
$data = [];
foreach ($result as $row) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
<script>
var dataSet = <?php echo json_encode($result); ?>;
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Title" },
{ title: "Office" },
{ title: "Salary" }
]
} );
} );
</script>
EDIT
As requested this is what my JSON looks like if I do a echo json_encode($data)
[{"Salesman":"Harris Teeter","Title":"Manager","Office":"Home","Salary":"0.000000"}]

First, you need to use data instead of title in datatable function.
$('#example').DataTable( {
data: dataSet,
columns: [
{ data: "Name" },
{ data: "Title" },
{ data: "Office" },
{ data: "Salary" }
]
} );
Second, you need to modify your JSON like below:
[{"Name":"Harris Teeter","Title":"Manager","Office":"Home","Salary":"0.000000"}]
Here is working JSFiddle : link

Related

datatables format values with text align

I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.

JSON Output File Format

I am using Canvasjs Charts to do my graphing from PHP / MySQL. Everything works as expected except for the creating of my JSON file.
Canvasjs requires the JSON file to look as follow:
callback({
"dps":
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
})
However, when creating my JSON file it is
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
All I want to know is how do I add the opening tag and closing tag in the sjon file from my script.
Here is the last part of my code that creates the JSON file:
$output_data= array();
while($row = mysqli_fetch_array($result))
{
$output_data[] = array(
'division' => $row["division"],
'units' => $row["units"]
);
}
return json_encode($output_data, JSON_NUMERIC_CHECK);
echo json_encode($output_data, JSON_NUMERIC_CHECK);
}
$file_name = 'myresult2'.'.json';
if(file_put_contents($file_name, get_data()))
{
echo $file_name. 'file created';
}
else
{
echo 'Error';
}
?>
Additional Data:
This is the code that generates the graph.
<script>
var chart = null;
var dataPoints = [];
window.onload = function() {
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light",
title: {
text: "Graph Header"
},
axisY: {
title: "% Verified",
titleFontSize: 12,
labelFontSize: 12,
valueFormatString: "#.##%"
},
axisX: {
title: "Division",
titleFontSize: 12,
labelFontSize: 12
},
data: [{
type: "column",
yValueFormatString: "#.##%",
dataPoints: dataPoints
}]
});
$.getJSON("myresult.json?callback=?", callback);
}
function callback(data) {
for (var i = 0; i < data.dps.length; i++) {
dataPoints.push({
label: data.dps[i].division,
y: data.dps[i].units
});
}
chart.render();
}
</script>
Please try
// change this
$output_data[] = array(
// to this
$output_data['dps'][] = array(
What you need to do is enclose you created array in a new array with a key named dps.
So after your while loop you should do something like this
$json_data['dps']=$output_data;
return json_encode($json_data, JSON_NUMERIC_CHECK);

DataTables - Dynamic Columns From Ajax Data Source?

I am trying to get DataTables to read the column names from an AJAX data source but it seems that there must be something that I must be missing here.
I made a fiddle fiddle in which I can manually define the data and columns that are being used by the table.
The table is declared in the HTML and there is no no need to define the column names (<thead>..</thead>):
<table id="example" class="display table table-striped table-bordered"
cellspacing="0" width="100%"></table>
In the JS we manually define the data:
var data = [
[ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
[ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
Then manually define the column names or titles:
var columns = [
{ "title":"One" },
{ "title":"Two" },
{ "title":"Three" }
];
Then when we initialise the table we simply pass the previously declared information across for DataTables to use:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
data: data,
columns: columns
});
});
Which results in:
Now my question is how would I get this to work if the data is included in the AJAX server side response?
I have tried this in various ways and forms but nothing really seems to work out here and I am battling to find relative documentation on this.
For example if the server side processing sent back a JSON response which includes the column names at the end:
{
"data": [
{
"id": "1",
"One": "Row 1 - Field 1",
"Two": "Row 1 - Field 2",
"Three": "Row 1 - Field 3"
},
{
"id": "2",
"One": "Row 2 - Field 1",
"Two": "Row 2 - Field 2",
"Three": "Row 2 - Field 3"
}
],
"options": [],
"files": [],
"columns": [
{
"title": "One",
"data": "One"
},
{
"title": "Two",
"data": "Two"
},
{
"title": "Three",
"data": "Three"
}
]
}
Given this is the response, I tried to configure DataTables to use an AJAX data source for the row information as follows:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
"ajax": '/test.php',
columns: columns
});
});
But obviously columns is undefined here.
So I get the column data before hand:
function getPromise() {
var deferred = $.Deferred();
var dataUrl = document.location.origin+'/text.php';
$.getJSON(dataUrl, function(jsondata) {
setTimeout(function() {
deferred.resolve(jsondata);
}, 0);
}).fail(function( jqxhr, textStatus, error ) {
// ********* FAILED
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
return deferred.promise();
}
// Get the columns
getPromise().done(function(jsondata) {
columns = jsondata.columns;
console.log(columns);
});
And pass it to DataTables as above. But this time all I get when running the example is an error in the console saying TypeError: p is undefined.
So then how could I make use of the dynamically generated columns that are being returned within the server side response? Is there not a simpler way to achieve this?
EDIT:
DataTables Editor code for server side processing / to generate the JSON response mentioned above:
<?php
// DataTables PHP library
require_once '/path/to/DataTables.php';
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
$out = Editor::inst( $db, 'example' )
->fields(
Field::inst( 'id' )->set(false),
Field::inst( '`One`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Two`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Three`' )->validator( 'Validate::notEmpty' )
)
->process( $_POST )
->data();
// On 'read' remove the DT_RowId property so we can see fully how the `idSrc`
// option works on the client-side.
if ( Editor::action( $_POST ) === Editor::ACTION_READ ) {
for ( $i=0, $ien=count($out['data']) ; $i<$ien ; $i++ ) {
unset( $out['data'][$i]['DT_RowId'] );
}
}
// Create the thead data
if (count ($out) > 0) {
$columns = array();
foreach ($out['data'][0] as $column=>$relativeValue) {
// Add all but the id value
if ($column !== 'id') {
// Add this column name
$columns[] = array(
"title"=>$column,
"data"=>$column
);
}
}
}
// Add the the thead data to the ajax response
$out['columns'] = $columns;
// Send the data back to the client
echo json_encode( $out );
If you don't use the built in DataTables ajax it should be easy enough given the structure of your data:
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data: {
json: JSON.stringify(jsonData)
},
success: function(d) {
$('#example').DataTable({
dom: "Bfrtip",
data: d.data,
columns: d.columns
});
}
});
});
Like this JSFiddle, you're limited then to loading all the data at once but that shouldn't be a huge issue... unless you alter it get the columns from the initial ajax call and once the DataTable is initiated then add the built-in ajax - I've not tried this though...
You must create the table in html without header
<table id="tablaListadoExpediciones" class="table table-bordered table-striped dt-responsive"> </table>
Now you have to generate the columns array dynamically. In this way, the columns will always be generated automatically even if the AJAX response varies over time.
function PintarTablaDinamicamente(datos) {//object "datos" comes from AJAX response
//I take the keys of the object as columns of the table
var arrColumnas = Object.keys(datos[0])
////In case you wanted to hide a column
//var indiceColumna = arrColumnas.indexOf("nameOfTheColumnToHide")
//if (indiceColumna !== -1) {
// arrColumnas.splice(indiceColumna, 1)
//}
var columns = []
//columns must be in JSON format-->{data:'keyToSearchInJSON',title:'columnTitle'}
for (var i in arrColumnas) {
//if (arrColumnas[i] == "SELECCIONAR") { //if you want to add a checkbox in one colunm (for example column named SELECT
// columns.push({
// data: null,
// defaultContent: '',
// className: 'select-checkbox',
// orderable: false
// });
//} else {
columns.push({ data: arrColumnas[i], title: arrColumnas[i] });
//}
}
tabla = $('#tablaListadoExpediciones').DataTable({
dom: "Blfrtip",
data: datos,
//order: [[0, 'desc']],
"pageLength": 25,
"scrollX": true,
columns: columns
,
buttons: [
{
extend: 'copy'
},
{
extend: 'excel'
},
{
extend: 'print'
}
],
//select: {
// style: 'os',
// selector: 'td:first-child'
//}
});
}

Jtable POST fails to send data (using PHP)

Having fun playing around with jtable,but got myself stuck in a bit of a rut.
I'm having a problem accessing data from a POST request. I'm trying to pass a variable from a field value in the table so I can make a custom SQL query.
My mainpage.php:
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Trip data';
ajaxSettings: {
type: 'POST'
},
actions: {
listAction: 'tableactions.php?action=list',
updateAction: 'tableactions.php?action=update',
deleteAction: 'tableactions.php?action=delete'
},
fields: {
user_id: {
key: true,
edit: false,
list: false
},
name: {
title: 'Name',
edit: false,
list: false
},
trip_id: {
title: 'Trip ID',
list: false,
edit: false
},
trip_name: {
title: 'Trip Name',
width: '50%'
},
time: {
title: 'Start time',
width: '25%',
edit: false
},
date: {
title: 'Start date',
width: '25%',
edit: false
}
}
});
//Load person list from server
$('#PeopleTableContainer').jtable('load');
});
I added the AJAX property to ensure it's set to post. Here's a portion of tableactions.php:
if($_GET["action"] == "list")
{
//Get user ID
$user_id = $_POST['user_id'];
//SQL query
$result = mysql_query("select * from userdata WHERE user_id=$user_id group by trip_id");
//Add selected records into an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
I've tried changing $user_id to a correct value manually and the table works and displays the correct information. Really racking my brains to try and solve this.
Have I missed something obvious? Why can't I get a value from $_POST?
Any help would be greatly appreciated!
I fixed this by cleaning my code and adding this into the table properties:
ajaxSettings: {
type: 'POST',
data: {'UserId': '<?php echo $userid;?>'},
url: './tableactions.php'
},
Works fine now.

json encoding php for fetching the data from the database ang showing it to te graph

I have written the following code for fetching the data from the database:
$result = mysql_query("select projid,projname,enddate,status from projects where kunnr='".$_SESSION["kunnr"]."'");
$model['dash']=array();
while($row = mysql_fetch_array($result)){
array_push($model['dash'],
array(
"id"=>$row["projid"],
"projname"=>$row["projname"],
"enddate"=>$row["enddate"],
"status"=>$row["status"],
));
}
and the following code for showing these data on the graph(chart)..
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1',
type: 'column'
},
title: {
text: 'Service Calls-Days Over'
},
xAxis: {
categories:[ <?php foreach($model["dashchart"] as &$obj){?>
'<?php echo $obj["name"];?>',
<?php }?>]
},
yAxis: {
},
series: [{
name: 'Service Calls-Days Over',
color:'#e48801',
data: [<?php foreach($model["dashchart"] as &$obj){?>
<?php echo $obj["days"];?>,
<?php }?>]
}
]
});
overhere i have used php coding but i want to do it by json encoding..
please suggest me...
use json_encode..
For example:
categories: <?php echo json_encode($model["dashchart"]); ?>
Please try with jQuery.getJSON http://api.jquery.com/jQuery.getJSON/ function.

Categories