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.
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
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.
I found cool realtime bandwidth monitor here: http://www.codejungle.org/site/Realtime+bandwidth+meter+with+php+and+jquery.html
What I tried to do is to modify the code so that it could show two series: download and upload speed.
I changed only the last few lines of code in data.php:
echo '[
{
label: "download",
data: ['.implode($_SESSION['rx'], ",").']
},
{
label: "upload",
data: ['.implode($_SESSION['tx'], ",").']
}
];';
But unfortunately it doesn't work, what's wrong with this piece of code?
Loose the outer brackets (they are already in the onDataReceived function) and the semicolon at the end:
echo '
{
label: "download",
data: ['.implode($_SESSION['rx'], ",").']
},
{
label: "upload",
data: ['.implode($_SESSION['tx'], ",").']
}
';
This is my first post, apologies if I've asked a question a number of people have already done so. I don't see the answer I need in other posts.
I'm using Flot Charts and have a SQL Server db, I've got a php file that will connect to the db and return all the values within the sql in an array.
<?php
$server = "XXXX";
$database = "XXXX";
$user = "ReportsUser";
$pwd = "ReportsUser";
$cnn = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $pwd);
if(!$cnn)
{
echo "error in connecting";
}
$sql = odbc_exec($cnn, "
SELECT Months
,Referrals
,ProjectedVol
FROM mis.ReferralsBudgetvsActual
WHERE Months <= MONTH(GETDATE())
");
while($result = odbc_fetch_array($sql))
{
$allreferrals[] = array($result['Months'],$result['Referrals'],$result['ProjectedVol']);
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
exit;
?>
This works well and produces the array as below
[[1,5981,7465],[2,5473,6962],[3,4974,7391],[4,5731,6985],[5,5891,7080],[6,5168,7136],[7,5551,7543],[8,4427,7242],[9,4617,7204],[10,4807,7642]]
Now, when it all comes together in the jquery file, this is where I end up getting stuck. I don't see where it pulls any other columns back apart from the first data column, how can this be done?
// document ready function
$(document).ready(function() {
var chartColours = ['#88bbc8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
// function for refreshing shiftstats chart
make_chart();
function make_chart() {
$.ajax({
cache: 'false',
type: 'GET',
dataType: 'json',
url: "test.php",
success: function(data) {
var d1 = data;
var d2 = data;
//define placeholder class
var placeholder = $(".shifts-chart");
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 20
},
series: {
grow: {
active: false,
stepMode: "linear",
steps: 50,
stepDelay: true
},
lines: {
show: true,
fill: false,
lineWidth: 4,
steps: false
},
points: {
show:true,
radius: 5,
symbol: "circle",
fill: true,
borderColor: "#fff"
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
}
},
yaxis: { min: 0 },
xaxis: {ticks:11, tickDecimals: 0},
colors: chartColours,
shadowSize:1,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
}
}
};
$.plot(placeholder,
[{
label: "Referrals",
data: d1,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
},
{
label: "ProjectedVol",
data: d2,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
}
], options);
}
});
}
});
Thanks
You'll need to change your php array creation to properly format the data into two series:
$d1 = array();
$d2 = array();
while($result = odbc_fetch_array($sql))
{
array_push($d1, array($result['Months'], $result['Referrals']));
array_push($d2, array($result['Months'], $result['ProjectedVol']));
}
$allreferrals = array($d1, $d2);
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
This should return it as an array of arrays:
[
[[1,5981],[2,5473],[3,4974],[4,5731],[5,5891],[6,5168],[7,5551],[8,4427],[9,4617,7204],[10,4807]],
[[1,7465],[2,6962],[3,7391],[4,6985],[5,7080],[6,7136],[7,7543],[8,7242],[9,7204],[10,7642]]
]
(Hopefully I have the syntax correct, I'm not a fan of php)
Update from comment
If you are returning a slew of series, you might be better returning an associative array from PHP:
$allreferrals = array('ref' => array(), 'projVol'=> array());
while($result = odbc_fetch_array($sql))
{
array_push($allreferrals['ref'], array($result['Months'], $result['Referrals']));
array_push($allreferrals['projVol'], array($result['Months'], $result['ProjectedVol']));
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
Then back in the javascript:
$.plot(placeholder,
[{
label: "Referrals",
data: data["ref"]
},
{
label: "ProjectedVol",
data: data["projVol"]
}],
options);