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.
Related
I want to get the row id to after sent it to php code,but im using datatables jquery plugin , however I show my id into datables , but datatables is generating td instead of inputs. if it were it will be easy to read it in php, but how can I read my row id of datable in php... I tried $_POST, but I cant because I havent any name on tds. other thing im using codeigniter. once I can read my id row I can use it for where id = id to update my item.
table
var table = $('#example').DataTable({
"lengthChange": false,
responsive: true,
dom: 'Blfrtip',
buttons: [{
extend: 'excelHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'csvHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'pdf',
exportOptions: {
columns: [1,2,3,4,5,6]
}
}],
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs:[{
targets: -1,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-pencil'></span></a>"
},{
targets: 6,
render: function (data) {
return (data == 1) ? "<span class='label label-success'>active</span>":"<span class='label label-danger'>inactive</span>";
}
}],
fnRowCallback: function (data,nRow) {
if (nRow[6] == 0) {
$(data).css({'background-color':'#f2dede'});
}else if(nRow[6] == 1){
$(data).css({'background-color':'#dff0d8'});
}else{
}
}
});
model
public function datatable(){
$this->db->select('id,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,storelte_articulos.status');
$this->db->from('storelte_articulos');
$query = $this->db->get();
return $query->result_array();
}
controller
public function datatable(){
$array = $this->products->datatable();
$this->json($array);
$data = array();
foreach ($array as $rows){
array_push($data, array(
$rows['id'],
$rows['descripcion'],
$rows['precio_compra'],
$rows['precio_venta'],
$rows['precio_mayoreo'],
$rows['existencia'],
$rows['status']
));
}
$this->json(array('data' => $data));
}
update controller
public function updateProduct($data){
$this->db->update('storelte_articulos',$data);
$this->db->where('id');
}
You need to put your ID into an input, but set it as hidden. That way the data isn't being shown to the end user, but it is available through post data.
As it is able to be seen with developer tools / inspect I would suggest encoding it for display then decoding it for use with the database queries.
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);
I use kendo UI grid and connect to Mysql,
the function update and read is OK, but when I use create, and input some data in new row, then I click the update but it has no effort.
I don't know what's wrong?
My grid is:
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "data/channels.php",
update: {
url: "data/channels.php",
type: "POST"
},
create: {
dataType: "json",
url: "data/channeladd.php",
type: "POST"
}
},
schema: {
data: "results",
model: {
id: "channelId",
fields: {
channelName: { validation: { required: true} }
}
}
}
},
columns: [{ field: "channelName", title: "Channel Name" }, { field: "channelIp", title: "Channel Ip" }, { field: "channelPort", title: "Channel Port" }, { command: ["edit", "destroy"], title: " ", width: "172px" }],
editable: "inline",
navigable: true, // enables keyboard navigation in the grid
toolbar: [ "create" ] // adds save and cancel buttons
});
And in channeladd.php:
$link = mysql_pconnect("localhost", "root", "THE PASSWORD") or die("Unable To Connect To Database Server");
mysql_select_db("THE DB") or die("Unable To Connect To THE DB");
// add the header line to specify that the content type is JSON
header("Content-type: application/json");
$request = json_decode(file_get_contents('php://input'));
// DISCLAIMER: It is better to use PHP prepared statements to communicate with the database.
// this provides better protection against SQL injection.
// [http://php.net/manual/en/pdo.prepared-statements.php][4]
// get the parameters from the get. escape them to protect against sql injection.
$channelnName = $request["channelName"];
$channelnIp = $request["channelIp"];
$channelnPort = $request["channelPort"];
$sql = "INSERT INTO channel (channelName, channelIp, channelPort) VALUES (".$channelnName.",".$channelnIp.",".$channelnPort.")";
$rs = mysql_query($sql);
if ($rs) {
echo true;
}
else {
header("HTTP/1.1 500 Internal Server Error");
echo false;
}
Any advice appreciated.
Sorry about that, I don't know the reason, but while I remove the line:
header("Content-type: application/json");
It becomes OK any operation. Thanks for attention, Deepu :)
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#ListContainer').jtable({
title: 'ITEM DETAILS',
actions: {
listAction: 'ListActions.php?action=list',
createAction: 'ListActions.php?action=create',
updateAction: 'ListActions.php?action=update',
deleteAction: 'ListActions.php?action=delete'
},
fields: {
item_id: {
title: 'item_id',
key: true,
list: false,
create: false,
width: '20%'
},
list_id: {
title: 'List_id',
width: '20%'
},
item_name: {
title: 'Item Name',
width: '20%'
},
description: {
title: 'Descriptions',
width: '20%'
}
}
});
//Load person list from server
$('#ListContainer').jtable('load');
});
</script>
this is my code..i want to pass id "listAction: 'ListActions.php?action=list'," here.. after i need to access that value in ListActions.php. how can i pass my id here?
i tried this way:
listAction: 'ListActions.php?action=list&id=$id',
here $id containing the retrieved value from database.
but this is not working.
Seems you have saved your page with .php extension. So pass 'id' argument within php tags like below:
actions: {
listAction: 'ListActions.php?action=list&id=<?php echo $id?>',
createAction: 'ListActions.php?action=create',
updateAction: 'ListActions.php?action=update',
deleteAction: 'ListActions.php?action=delete'
},
and on server side,since data is sent as GET parameters,use following:
$id = $_GET['id'];
You can use something like this
//Load person list from server
$('#ListContainer').jtable('load',
{
id1: <?php echo $_GET['id1'] ?>,
id2: <?php echo $_GET['id2'] ?>
}
);
Please mark as answer if this solution can solve your problem.
I am trying to use flot to plot some data that is pulled from a MySQL db. I am log users login visits and I have a SQL function that will retreive the number of visits per day for a given month, getStats($day). I have read some examples online how to properly do this but for some reason when I try and graph the array data in my javascript file ' it comes up empty --> 'data: '. Below is my code. I am using the CI framework so if there are some questions about my code it is most likely because of that. I have hardcoded data in and it works fine. Any help on this matter would be appreciated there is not much about using flot with databases out there currently.
Model---> metrics.php
function showUsers() {
//get the number of days in the current month and the first day
$num_days = cal_days_in_month(CAL_GREGORIAN, date(m), date(Y));
$first_day = strtotime(date('Y').'-'.date('m').'-01');
//iterate through all of the days
while( $i < $num_days ) {
//get the user visits for each day of the month
$log = $this->db->getStats($first_day);
//add +1 day to the current day
$first_day += 86400;
$flot_visits[] = '['.($first_day*1000).','.$log->fields['total'].']';
$i++;
}
//format in acceptable format for flot
$content['visits'] = '['.implode(',',$flot_visits).']';
//load the view and pass the array
$this->load->vars($content);
$this->load->view('metrics/user_metrics', $content);
}
View ---> user_metrics.php
<div id ="visits_graph" style="width:600px; height:300px"></div>
Javascript ---> user_metrics.js
function metrics() {
$.ajax({
type: "POST",
url: pathurl + "metrics/showUsers",
data: "",
success: function(data) {
graph_visits();
}
});
}
function graph_visits() {
$.plot($('#visits_graph'), [
{ label: 'Visits', data: <?php echo $visits ?> }
], {
xaxis: {
mode: "time",
timeformat: "%m/%d/%y"
},
lines: { show: true },
points: { show: true },
grid: { backgroundColor: #fffaff' }
});
}
I think your problem is within the metrics function. (also I am guessing you are using JQuery)
At the moment your metrics function requests a page at the backend but does nothing with it.
change the backend method showUsers() to be something like:
function showUsers() {
//get the number of days in the current month and the first day
$num_days = cal_days_in_month(CAL_GREGORIAN, date(m), date(Y));
$first_day = strtotime(date('Y').'-'.date('m').'-01');
//iterate through all of the days
while( $i db->getStats($first_day);
//add +1 day to the current day
$first_day += 86400;
//change this to be a nested array
$flot_visits[] = array( ($first_day*1000) , $log->fields['total'] );
$i++;
}
//output javascript array
echo json_encode( $flot_visits );
}
change user_metrics.js to be something like :
function metrics() {
$.getJSON({
pathurl + "metrics/showUsers",
function(data) {
//use the returned data
graph_visits(data);
}
});
}
function graph_visits( graphData ) {
$.plot($('#visits_graph'), [
{ label: 'Visits', data: graphData }
], {
xaxis: {
mode: "time",
timeformat: "%m/%d/%y"
},
lines: { show: true },
points: { show: true },
grid: { backgroundColor: #fffaff' }
});
}
I got it to work but not the way I would like it. I figured I would post the answer so if anyone else runs into this issue they can get it to at least work.
So for some reason and I am assuming because the javascript file and the actual view(html) file are separated due to the framework that the array is not visible to the javacscript file. The issue lies within the function
function graph_visits() {
$.plot($('#visits_graph'), [
{ label: 'Visits', data: <?php echo $visits ?> }
], {
xaxis: {
mode: "time",
timeformat: "%m/%d/%y"
},
lines: { show: true },
points: { show: true },
grid: { backgroundColor: #fffaff' }
});
}
because they are seperate
<?php echo $visits ?>
returns nothing. The way I fixed it was just go into the view and just copy and past the contents of the function between two tags at the top of the html file. It should look like this,
<script language="javascript">
$.plot($('#visits_graph'), [
{ label: 'Visits', data: <?php echo $visits ?> }
], {
xaxis: {
mode: "time",
timeformat: "%m/%d/%y"
},
lines: { show: true },
points: { show: true },
grid: { backgroundColor: #fffaff' }
});
</script>
I do not really like this solution because it is breaking away from the framework but so far it the only solution I have been able to come up with.