jqgrid edit cell and save to database - php

I am using jqgrid and trying to edit a cell and update the value to table in database, but im missing something and couldnt make it work. please help me to correct if im missing something.below is the code for your reference. please help. thanks in advance.
HTML
$qr="SELECT id,`emp_id`,`emp_name`, `att_date`, `emp_join_date`, `intime`,`outtime`,`Total_Hours`,`OT Hours`,`Status` FROM `db_emp_attendance` WHERE Status='Absent' and att_date='2017-04-01'";
$q = mysql_query($qr);
$rows = array();
while($r = mysql_fetch_assoc($q)) {
$rows[] = $r;
}
$json_data=json_encode($rows);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/ecmascript" src="jquery.min.js"></script>
<script type="text/ecmascript" src="jquery.jqGrid.min.js"></script>
<script type="text/ecmascript" src="grid.locale-en.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="jquery-ui.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="ui.jqgrid.css"/>
<meta charset="utf-8" />
</head>
<body>
<table id="rowed5"></table>
<script type="text/javascript">
var lastsel2
jQuery("#rowed5").jqGrid({
datatype: "local",
height: 400,
autowidth: true,
colNames:['ID','Emp ID','Name', 'Join Date','Attendance Date', 'Time In','Time Out','Total Hours','OT Hours','Status','leave_type'],
colModel:[
{name:'id',index:'id', width:75,align:"center",key: true},
{name:'emp_id',index:'emp_id', width:75,align:"center"},
{name:'emp_name',index:'emp_name', width:150,align:"left"},
{name:'emp_join_date',index:'emp_join_date', width:150,align:"center"},
{name:'att_date',index:'att_date', width:100, align:"center"},
{name:'intime',index:'intime', width:80,align:"center"},
{name:'outtime',index:'outtime', width:80,align:"center"},
{name:'Total_Hours',index:'Total_Hours', width:80,align:"center"},
{name:'OT Hours',index:'OT Hours', width:80,align:"center"},
{name:'Status',index:'Status', width:150,align:"center"},
{name:'leave_type',index:'leave_type', width:150, sortable:false,editable: true,
edittype: "select",
editoptions: {
value: "SickLeave:SickLeave;DayOff:DayOff;Vacation:Vacation"}
}
],
onSelectRow: function(id){
if(id && id!==lastsel2){
jQuery('#rowed5').jqGrid('restoreRow',lastsel2);
jQuery('#rowed5').jqGrid('editRow',id,true);
lastsel2=id;
}
},
editurl:'update.php',
caption: "Attendance"
});
var mydata2 =<?PHP echo $json_data;?>;
for(var i=0;i < mydata2.length;i++)
jQuery("#rowed5").jqGrid('addRowData',mydata2[i].id,mydata2[i]);
</script>
</body>
</html>
DB UPDATE PHP FILE
if($_POST['oper']=='edit')
{
$id = mysql_real_escape_string($_POST['id']);
$leave_type = mysql_real_escape_string($_POST['leave_type']);
$sql = "UPDATE db_emp_attendance SET leave_type = '$leave_type' WHERE id = '$id'";
mysql_query($sql);
}

i found a solution and now it is updating in database. i had to add cellEdit : true, cellsubmit : 'remote', cellurl : 'update.php'

Related

Disable dates and time in a jquery time from mysql

Update This is a complete update to my question
<!doctype html>
<html>
<meta charset="utf-8">
<meta name="author" content="Amsul - http://amsul.ca">
<meta name="viewport" content="width=device-width,user-scalable=no">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Pickadate.js</title>
<link rel="stylesheet" href="../../lib/themes/default.css">
<link rel="stylesheet" href="../../lib/themes/default.date.css">
<link rel="stylesheet" href="../../lib/themes/default.time.css">
<!--[if lt IE 9]>
<script>document.createElement('section')</script>
<style type="text/css">
.holder {
position: relative;
z-index: 10000;
}
.datepicker {
display: block;
}
</style>
<![endif]-->
<body>
<?php
require 'connect-db.php';
try{
$stmt = $db->query("SELECT ddate FROM testdates");
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}catch(\PDOException $e){
echo $e->getMessage();
}
$json_array = json_encode($result)
?>
<section class="section">
<form>
<fieldset>
<h3><label for="datepicker_id">Pick a date.</label></h3>
<input
id="datepicker_id"
class="datepicker"
name="date"
type="text"
value=""
data-value="">
<br><br><br><br><br>
<h3><label for="timepicker_id">Pick a time</label></h3>
<input
id="timepicker_id"
class="timepicker"
value=""
type="time"
name="time">
<!-- valuee="2:30 AM"
data-value="0:00" -->
<!-- <button type="button">Disable all dates</button>
<input class="button" type="submit" value="open"> -->
</fieldset>
</form>
<div id="container"></div>
</section>
<script src="../jquery.1.9.1.js"></script>
<script src="../../lib/picker.js"></script>
<script src="../../lib/picker.date.js"></script>
<script src="../../lib/picker.time.js"></script>
<script src="../../lib/legacy.js"></script>
<script type="text/javascript">
//datepicker
var disdates = <?php echo $json_array; ?>
var $input = $( '.datepicker' ).pickadate({
formatSubmit: 'yyyy/mm/dd',
min: true,
container: '#container',
// editable: true,
closeOnSelect: true,
closeOnClear: false,
disable: [ disdates
]
})
var picker = $input.pickadate('picker')
// picker.set('select', '14 October, 2014')
// picker.open()
// $('button').on('click', function() {
// picker.set('disable', true);
// });
</script>
<script type="text/javascript">
//timepicker
var dtimes = new Date(2015,11,28,5,30);
var $timeinput = $( '.timepicker' ).pickatime({
disable: [
[2,0],
dtimes
]
})
var timepicker = $timeinput.pickatime('picker')
</script>
</body>
</html> // i must thank users in php chatroom for helping me fix the errors.
That above, is a page where you see a calendar, and some dates are disabled, which are fetched from the database. I'm using this picker
disable: [
[2015,29,9], // disables today strangely month -1 and only accepts yyy,mm,dd
[some other array]
]
})
In my databese 'ddate' is varchar, no primary key, no unique id, nothing, containing
2015,9,30
2015,9,31
2015,10,30
the values aren't being passed or something from mysql to javascript or something, and i guess i want multidimentional array.
what i want the javascript array to have is month -1 because as I explained above, in disable option to disable this day, you have to enter last month number. and if first month, means 12.
Note I want to use the same for timepicker but I guess I could do on my own if I understand the issue with calendar
I assume, that your db content is:
ddate: varchar()
Values stored in table testdates (as strings):
2015-10-29
2015-10-15
2015-10-10
Select is still as is plus create a string for array build to js
try{
$stmt = $db->query("SELECT ddate FROM testdates");
$db_ddates = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$js_ddates = "";
foreach ($db_ddates as $row => $record) {
$js_ddates .= '"' . $record['ddate'] . '",';
}
}
catch(\PDOException $e) {
echo $e->getMessage();
}
Now use that inside building the script part
// take dates as array of strings from db
var ddates_str_arr = [ <?php echo $js_ddates; ?> ];
// build dates array for picker
var disdates = [];
for (var i = 0; i < ddates_str_arr.length; i++) {
disdates.push(new Date(ddates_str_arr[i]));
}
// just use it in picker
var $input = $( '.datepicker' ).pickadate({
formatSubmit: 'yyyy/mm/dd',
min: true,
container: '#container',
// editable: true,
closeOnSelect: true,
closeOnClear: false,
disable: disdates
});
ATTENTION: I have not test it but just write those lines from mind. There may some typing erratas but should work in general.
UPDATE:
Not sure about picker but give this a try too instead of the above script part
// just use it in picker
var $input = $( '.datepicker' ).pickadate({
formatSubmit: 'yyyy/mm/dd',
min: true,
container: '#container',
// editable: true,
closeOnSelect: true,
closeOnClear: false,
disable: [ <?php echo $js_ddates; ?> ]
});

Loading data to jqGrid using AJAX and PHP

I have the following code in browser side.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script src="js/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<link href="css/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="css/ui.jqgrid.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="css/jqGrid.css" rel="stylesheet" type="text/css" media="screen"/>
<script type="text/javascript">
$(document).ready(function () {
$("#tblevents").jqGrid({
url: "getGridData.php",
datatype: "json",
mtype: "POST",
postData: {
search: function() { return 'manage'; }
},
colModel: [
{name:'id',index:'id',label:'ID', width:10},
{name:'eventdate',index:'eventdate',label:'Event date', width:100, align:'center', sorttype:'date'},
{name:'reportdate',index:'reportdate',label:'Report date', width:180, align:'left'},
{name:'eventdescription',index:'eventdescription',label:'Description', width:430}
],
rowNum: 10,
rowList: [10,20],
pager: '#pager',
height: '100%',
width: 'autowidth',
viewrecords: true,
gridview: true,
caption: "ATM-ANS Occurrences"
});
});
</script>
</head>
<body>
<div class="mycenter">
<table id='tblevents'></table>
<div id='pager'></div>
</div>
</body>
</html>
The server side code.
<?php
$sqconn = "mysql:host=localhost;dbname=eoccurrence";
$dbh = new PDO($sqconn, 'user', '');
$page = $_POST['page'];
$limit = $_POST['rows'];
$sidx = $_POST['sidx'];
$sord = $_POST['sord'];
if(!$sidx) {$sidx =1;}
try {
$SQLQues = "SELECT COUNT(*) AS count FROM event";
$cmd = $dbh->query($SQLQues, PDO::FETCH_ASSOC);
$res = $cmd->fetchAll();
$count = $res[0]['count'];
if( $count > 0 && $limit > 0) {$total_pages = ceil($count/$limit);}
else {$total_pages = 0;}
if ($page > $total_pages) {$page=$total_pages;}
$start = $limit*$page - $limit;
if($start <0) {$start = 0;}
$SQLQues = "SELECT ID, date_format(eventdate, '%d-%m-%Y %H:%i') AS eventdate, " .
"date_format(reportDate, '%d-%m-%Y') AS reportdate, SUBSTRING(eventdescription,1,70) AS eventdescription " .
"FROM event" .
" ORDER BY event.eventdate DESC LIMIT $start , $limit";
$cmd = $dbh->query($SQLQues, PDO::FETCH_BOTH);
$i=0;
while ($row = $cmd->fetch()) {
$responce->rows[$i]['id']=$row['ID'];
$responce->rows[$i]['cell']=array($row['eventdate'],$row['reportdate'],$row['eventdescription']);
$i++;
}
echo json_encode($response);
return;
} catch (PDOException $exc) {
echo $exc->getTraceAsString();
}
The $response that is encoded from php to browser is shown in the following image, capture with XDebug.
The resulting grid is as shown below, with no row data at all.
What I'm doing wrong?
<script type="text/javascript">
$(document).ready(function () {
$("#tblevents").jqGrid({
url: "getGridData.php",
datatype: "json",
mtype: "POST",
colNames: ["Id","eventdate", "reportdat", "event
description"],
colModel: [
{name:'id'},
{name:'eventdate'},
{name:'reportdate'},
{name:'eventdescription'}
],
pager: "#pager",
rowNum: 10,
rowList: [10,20],
sortorder: "asc",
height: 'auto',
viewrecords: true,
gridview: true,
caption: "ATM-ANS Occurrences"
});
});

passing array to flot

I have been trying to make a graph plot with flot, and have ran into a problem.I Think the problem is with the way m using the php variable with flot Aside from that the graph isn't showing so I must have done something wrong. Below is the graph code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="./flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.categories.js"></script>
</head>
<body>
<?php
//CONNECTING TO THE SERVER
$servername = "XXX";
$username = "YYY";
$password = "ZZZ";
conn = new mysqli($servername, $username, $password);
$sql = "SELECT NAME, AGE FROM pro_db";
$result = $conn->query($sql);
$wt=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//storing the values in the array
$wt[]=$row;//is this the right way
}
} else {
echo "0 results";
}
?>
<div id="placeholder" style="width:600px;height:300px;"></div>
<script type="text/javascript">
$(function () {
//accessing the array
var data = <?php echo $wt; ?>;
$.plot($("#placeholder"), [data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center" }
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
});
</script>
</body>
</html>``
Here's completely working example i made. If something doesn't work - there's some error with data. Try var_dump how your $wt array looks like in the end;
$data = [
['Andrew', 31],
['Helen', 29],
['Dasha', 24],
['Denis', 23]
];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="canvas" style="width: 600px; height: 400px;"></div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/flot/jquery.flot.js"></script>
<script src="bower_components/flot/jquery.flot.categories.js"></script>
<script>
var data = <?php echo json_encode($data) ?>;
$("#canvas").plot([data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
</script>
</body>
</html>

Flot graph not showing

I am pulling data from a mySql database using php to plot a graph using flot. The query works fine but no graph is being displayed when I run the code. A blank space is coming up where the graph should be. Here is what I have:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Graph</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Flot Graph</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$mysqli=new mysqli('localhost','root',"",'simpledb');
$sql="select name, age from `people` where age=23";
$results = $mysqli->query($sql);
if ($results)
{
while ($row=$results->fetch_assoc())
{
$dataset1[] = array($row['name'],$row['age']);
}
}
else
{
echo "Error";
}
?>
<script type="text/javascript">
var dataset1 = <?php echo json_encode($dataset1); ?>;
$(function ()
{
$.plot($("#placeholder"), [
{
data: dataset1,
bars: {show: true}
}
]);
});
</script>
</body>
</html>
It looks like your x values are strings, yet you haven't included the categories plugin.
Thanks everyone. I got it to work. I'm not sure what the problem was but it worked after I changed the javascript part to :
$(function ()
{
$.plot("#placeholder", [ dataset1 ], {
series: {
bars: {
show:true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength:0
}
});
});

Sending Jquery value to PHP page

I'm really struggling to get this working so any help would be much appreciated!
Basically I have a JQGRid that displays bookings with double click event as follows:
ondblClickRow: function(rowid)
{
rowData = $("#bookings").getRowData(rowid);
var brData = rowData['bookref'];
getGridRow(brData);
},
This gets passed to getGridRow function:
function getGridRow(brData) {
$.ajax({
url: 'bookings-dialog.php',
data: {'rowdata' : brData },
dataType: 'json', //this is what we expect our returned data as
error: function(){
alert("It failed");
$('#cp-div-error').html('');
$('#cp-div-error').append('<p>There was an error inserting the data, please try again later.</p>');
$('#cp-div-error').dialog('open');
},
success: function(data){
//empty our dialog so we don't end up with duplicate content
$('.cp-booking-info').empty();
//we have told the browser to expect JSON back, no need to do any parsing
//the date
$('.cp-booking-info').append('<p class="pno-margin">Booking Date: '+data.bookref+'</p>');
//now let's manipulate our dialog and open it.
$("#cp-bookings-dialog").dialog({
show: { effect: 'drop', direction: "up" },
hide: 'slide',
height: 625,
width: 733,
title: 'Booking Reference: - '+ brData
});
}
});
And this is the bookings-dialog.php:
<?php
require_once('deployment.php');
require_once('bootstrp/all.inc.php');
require_once('models/sql.php');
require_once('models/bookingdocket.php');
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$rowdata = $_POST['rowdata'];
$query = ("SELECT * FROM tblbookings WHERE bookref = '$rowdata'");
$stmt = $dbh->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_BOTH);
BookingDocket::set_id($row['id']);
BookingDocket::set_bookref($row['bookref']);
BookingDocket::set_bookdate($row['bookingdate']);
BookingDocket::set_returndate($row['returndate']);
BookingDocket::set_journeytype($row['journeytype']);
BookingDocket::set_passtel($row['passengertel']);
BookingDocket::set_returndate($row['returndate']);
$booking_ref = BookingDocket::get_bookref();
return json_encode(array('bookref' => $booking_ref,
)
);
$stmt->closeCursor();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
$dbh = null;
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title Work</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="lib/jq-ui/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" href="lib/jq-grid/ui.jqgrid.css" />
<script type="text/javascript" src="scripts/js/utils/util-sha256.js"></script>
<script type="text/javascript" src="lib/jq-core/jquery-1.4.4.min.js" ></script>
<script type="text/javascript" src="lib/jq-ui/jquery-ui-1.8.16.custom.min.js" ></script>
<script type="text/javascript" src="lib/jq-grid/grid.locale-en.js"></script>
<script type="text/javascript" src="lib/jq-grid/jquery.jqGrid.min.js" ></script>
<script type="text/javascript" src="scripts/js/interface-datagrids.js"></script>
<script type="text/javascript" src="scripts/js/image-preload.js"></script>
<script type="text/javascript" src="scripts/js/general-interface.js" ></script>
<script type="text/javascript" src="scripts/js/general-controlpanel.js" ></script>
<script type="text/javascript" src="scripts/js/general-validation.js"></script>
</head>
<body>
<div id="cp-bookings-dialog">
<div class="cp-tiles-wrapper-dlg">
<div class="cp-booking-info left">
</div>
</div>
</div>
</body>
</html>
What I am trying to achieve is that when you double click a booking, the booking reference (e.g. BR12345) is passed to bookings-dialog.php and used in the the query (e.g. SELECT * FROM tblbookings WHERE bookref = '$rowdata'). I have been trying to use JSON to achieve this but at the moment when I double click a row, it is just failing at the moment and I am unsure why.
Any suggestions?
Try:
$.ajax({
type: 'POST', //ADD THIS .ajax defaults to GET and in the php you expect POST
url: 'bookings-dialog.php',
data: {'rowdata' : brData },
The default HTTP type for AJAX calls is a GET. You should change to a POST.
$.ajax({
type:'POST',
...
http://api.jquery.com/jQuery.ajax/

Categories