I can generate now highcharts calling data with mysql. Now I plot splines, but I need to combine 2 splines (for TMax and TMin) and 1 column (for Rain). Anybody knows what I should change in the next two files, I guess in index.php ? I can do plot this combination using csv files but now with mysql. Any idea?
Code of mysql-highcharts.php
<?php
session_start();
$con = mysqli_connect("xxxx","xxx","xxx","xxx");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_set_charset($con, 'utf8');
function split($date){
$day=substr($date,0,2);
$month=substr($date,3,2);
$year=substr($date,6,4);
return $year . "/" . $month . "/" . $day;
}
$sth = mysqli_query($con,"SELECT City,TMax FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Data");
$rows = array();
$rows['name'] = 'TMAX';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['TMax'];
}
$sth = mysqli_query($con,"SELECT City,TMin FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Data");
$rows1 = array();
$rows1['name'] = 'TMIN';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
$sth = mysqli_query($con,"SELECT City,Rain FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Data");
$rows2 = array();
$rows2['name'] = 'RAINS';
while($rr = mysqli_fetch_assoc($sth)) {
$rows2['data'][] = $rr['Rain'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Code of index.php (highcharts code)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
<?php
$city = $_POST["City"];
session_start();
$_SESSION['City'] = $_POST['City'];
$_SESSION['date8'] = $_POST['date8'];
$_SESSION['date9'] = $_POST['date9'];
?>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("mysql-highcharts.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'TMax-TMin-Rain <?php echo $city ?>',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Temperature (ºC)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Simply set for that specific series type, like this:
$rows1 = array();
$rows1['name'] = 'TMIN';
$rows1['type'] = 'column';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
Related
I am gathering live data from a mysql database using php and ajax. I want the data to be live updated every 2 seconds.
My code displays the chart and data as I want it, but does not live update the data from the database. The piece of code meant to be doing that is:
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
And I think the error lies somewhere there as when I inspect the element with google chrome it tells me "Uncaught TypeError: Cannot read property 'reload' of undefined".
Here is the full JS code:
<script type="text/javascript">
// load chart lib
google.load('visualization', '1', {
packages: ['corechart']
});
// call drawChart once google charts is loaded
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "php/connection3_temp.php",
dataType:"json",
async: true
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Ambient Temp.');
data.addColumn('number', 'Object Temp.');
data.addColumn('number', 'Humidity');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.amb_temp),
parseFloat(row.obj_temp),
parseFloat(row.hum)
]);
});
var options = {
title: 'Temperature and Humidity against Time',
legend: { position: 'bottom' },
series: {
0: {targetAxisIndex: 0},
1: {targetAxisIndex: 0},
2: {targetAxisIndex: 1}
},
vAxes: {0: {title: 'Temp. (°C)',
minValue: 0,
maxValue: 30
},
1: {title: 'Humidity (%)',
minValue: 20,
maxValue: 80
}
},
hAxis: {
title: 'Time (s)'
},
};
var chart = new google.visualization.LineChart($('#temp_chart').get(0));
chart.draw(data, options);
});
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
}
</script>
and also the PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "raspberryblue";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM sensortag3 ORDER BY id DESC LIMIT 3000";
$result = $conn->query($sql);
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysqli_error() . "<br>";
$message .= 'Whole query: ' . $sql;
die( $message );
}
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "timestamp": "' . $row['timestamp'] . '",' . "\n";
echo ' "amb_temp": "' . $row['amb_temp'] . '",' . "\n";
echo ' "obj_temp": "' . $row['obj_temp'] . '",' . "\n";
echo ' "hum": "' . $row['hum'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
$conn->close();
?>
There's no property named reload() in your script. That's why the console is showing undefined property reload(). So add the reload method inside ajax() for refreshing the data.
Someone who knows about JTable? I´ve tried to create a specfici table with this plugin however I can´t find the right way. I donwloaded the examples and modify it for my needs. But after change the code I have a blank page only in the browser.
Can someone explain to me where is/are the mistake/s?
index.php
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Table of people',
paging: true,
pageSize: 50,
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: 'PersonActionsPagedSorted.php?action=list',
createAction: 'PersonActionsPagedSorted.php?action=create',
updateAction: 'PersonActionsPagedSorted.php?action=update',
deleteAction: 'PersonActionsPagedSorted.php?action=delete'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false,
width: '5%',
},
Fecha: {
title: 'Fecha',
width: '10%',
type: 'date',
}
Nombre: {
title: 'Nombre',
width: '10%',
options: { '1': 'Option1', '2': 'Option2', '3': 'Option3','4': 'Option4' }
},
Turno: {
title: 'Turno',
width: '10%',
options: { '1': 'Option1', '2': 'Option2', '3': 'Option3'}
},
Info: {
title: 'Info',
width: '45%',
type: 'textarea'
},
Estado: {
title: 'Estado',
width: '10%',
options: { '1': 'Option1', '2': 'Option2', '3': 'Option3'}
},
Criticidad: {
title: 'Criticidad',
width: '10%',
options: { '1': 'Option1', '2': 'Option2', '3': 'Option3'}
},
}
});
//Load person list from server
$('#PeopleTableContainer').jtable('load');
});
</script>
PersonActionsPagedSorted.php
<?php
try
{
//Open database connection
$con = mysql_connect("localhost","root","");
mysql_select_db("jtabletestdb", $con);
//Getting records (listAction)
if($_GET["action"] == "list")
{
//Get record count
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM people;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM people ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
else if($_GET["action"] == "create")
{
//Insert record into database
$result = mysql_query("INSERT INTO people(Fecha, Nombre, Turno, Info, Estado, Criticidad) VALUES('" . $_POST["Fecha"] . "', '" . $_POST["Nombre"] . "','" . $_POST["Turno"] . "', '" . $_POST["Info"] . "','" . $_POST["Estado"] . "', '" . $_POST["Criticidad"] . ";");
//Get last inserted record (to return to jTable)
$result = mysql_query("SELECT * FROM people WHERE PersonId = LAST_INSERT_ID();");
$row = mysql_fetch_array($result);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
//Updating a record (updateAction)
else if($_GET["action"] == "update")
{
//Update record in database
$result = mysql_query("UPDATE people SET Fecha = '" . $_POST["Fecha"] . "', Nombre = '" . $_POST["Nombre"] . "', Turno = '" . $_POST["Turno"] . "', Info = '" . $_POST["Info"] . "',Estado ='" . $_POST["Estado"] . "', Criticidad = '" . $_POST["Criticidad"]. "' WHERE PersonId = " . $_POST["PersonId"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Deleting a record (deleteAction)
else if($_GET["action"] == "delete")
{
//Delete from database
$result = mysql_query("DELETE FROM people WHERE PersonId = " . $_POST["PersonId"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Close database connection
mysql_close($con);
}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
print json_encode($jTableResult);
}
?>
If you wonder, yeah I´m very novice in this world and I suppose the answer is simple.
It's hard to implement a search method in a jTable.
Codes:
generaterecords.php:
<?php
$page_title = "Generate Reports";
require_once('template/header.php');
require_once('template/navmenu.php');
require_once('template/content-top.php');
?>
<div class="filtering">
<form>
<select name="year" >
<option value="0000">Year</option>
<?php
for($i=date('Y'); $i>2012; $i--) {
echo '<option value="'.$i.'"'.'>'.$i.'</option>'."\n";
}
?>
</select>
<select name="month">
<option value="0">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<button type="submit" id="LoadRecordsButton">Load records</button>
</form>
<div id="PeopleTableContainer" style="width: 850px;"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Payment Records',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'payment.paymentdate ASC',
actions: {
listAction: 'payment.php?action=list'
},
fields: {
paymentid: {
key: true,
create: false,
edit: false,
list: false
},
lname: {
title: 'Last Name',
width: '20%',
create: false,
edit: false
},
fname: {
title: 'First Name',
width: '20%',
create: false,
edit: false
},
mname: {
title: 'Middle Name',
width: '20%',
create: false,
edit: false
},
paymenttype: {
title: 'Type',
width: '20%',
create: false,
edit: false
},
paymentdate: {
title: 'Date',
width: '20%',
create: false,
edit: false
},
totalrate: {
title: 'Total Rate',
width: '20%',
create: false,
edit: false
},
paymentamt: {
title: 'Amount',
width: '20%',
create: false
},
balance: {
title: 'Balance',
width: '20%',
create: false,
edit: false
}
}
});
//Load person list from server
//$('#PeopleTableContainer').jtable('load');
//Re-load records when user click 'load records' button.
// Backup
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#PeopleTableContainer').jtable('load', {
year: $('#year').val(),
month: $('#month').val()
});
});
//Load all records when page is first shown
// $('#LoadRecordsButton').click();
});
</script>
<br>
<br>
<?php
// footer
require_once('template/footer.php');
?>
payment.php:
<?php
include_once ('database_connection.php');
try
{
$con = mysql_connect("localhost","kureido","tnx4standinstillwanker");
mysql_select_db("kureido", $con);
//Getting records (listAction)
if($_GET["action"] == "list")
{
//Get record count
$offresult = mysql_query("SELECT COUNT(*) AS OLRecordCount FROM official;");
$offrow = mysql_fetch_array($offresult);
$allresult = mysql_query("SELECT COUNT(*) AS AllRecordCount FROM lodger;");
$allrow = mysql_fetch_array($allresult);
$resresult = mysql_query("SELECT COUNT(*) AS ResRecordCount FROM reservation;");
$resrow = mysql_fetch_array($resresult);
$recordCount = $allrow['AllRecordCount'] - $offrow['OLRecordCount'] - $resrow['ResRecordCount'];
$year = "";
$month = "";
if (empty($_POST['year']) && empty($_POST['month']))
$year = $month = "";
else
{
$year = $_POST['year'];
$month = $_POST['month'];
}
//Get records from database
$result = mysql_query("SELECT payment.paymentid, lodger.ssn, lodger.lname, lodger.fname, lodger.mname, payment.paymenttype, payment.paymentdate, payment.totalrate, payment.paymentamt, payment.totalrate - payment.paymentamt AS balance FROM payment, lodger WHERE lodger.ssn = payment.lodger_ssn AND YEAR(paymentdate) = '" . $_POST["year"] . "' AND MONTH(paymentdate) = '" . $_POST["month"] . "' ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] .";");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
/* else if($_GET["action"] == "create")
{
//Insert record into database
$result = mysql_query("INSERT INTO people(Name, Age, RecordDate) VALUES('" . $_POST["Name"] . "', " . $_POST["Age"] . ",now());");
//Get last inserted record (to return to jTable)
$result = mysql_query("SELECT * FROM people WHERE PersonId = LAST_INSERT_ID();");
$row = mysql_fetch_array($result);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
} */
//Updating a record (updateAction)
else if($_GET["action"] == "update")
{
//Update record in database
$result = mysql_query("UPDATE official SET room_code = '" . $_POST["room_code"] . "', appliancerate = '" . $_POST["appliancerate"] . "', monthlybal = '" . $_POST["monthlybal"] . "' WHERE lodger_ssn = " . $_POST["ssn"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Deleting a record (deleteAction)
else if($_GET["action"] == "delete")
{
//Delete from database
$result = mysql_query("DELETE FROM official WHERE lodger_ssn = " . $_POST["ssn"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
else if($_GET["action"] == "view")
{
}
//Close database connection
mysql_close($con);
}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
print json_encode($jTableResult);
}
?>
Sometimes the server returns errors. Any ideas on how to get this fixed? generaterecords.php is the client side while payment.php is the server side.
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#PeopleTableContainer').jtable('load', {
year: $('#year').val(),
month: $('#month').val()
});
});
//remove your comments .. the code below is for running the function above when loadrecords button is clicked
$('#LoadRecordsButton').click();
I'm just learning how to use the google maps with info from my database, and i'm having some trouble. I can get the map to appear with no problem, and the info from my database is being pulled correctly in the php page, but i can't seem to call that information in my html page. I'm trying to get little icons to appear on the map at each location in the database, but so far, nothing is appearing other than the google maps box. Any help would be greatly appreciated!
googleMap.php
<?
$username="myUsername";
$password="myPassword";
$database="myDatabase";
?>
<?php
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Start XML file, echo parent node
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo 'marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
?>
googleMap.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl(googleMap.php, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
/body>
</html>
IN your PHP file you're echoing every row. But the markup is not correct. It should be a proper xml-node, you're displaying just some text.
header("Content-type: text/xml");
// Start XML file, create parent node
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("markers");
$parnode = $doc->append_child($node);
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $doc->create_element("marker");
$newnode = $parnode->append_child($node);
$newnode->set_attribute("name", $row['name']);
$newnode->set_attribute("address", $row['address']);
$newnode->set_attribute("lat", $row['lat']);
$newnode->set_attribute("lng", $row['lng']);
$newnode->set_attribute("type", $row['type']);
}
See this link: https://developers.google.com/maps/articles/phpsqlajax_v3#outputxml
I'm new to use jqGrid and there is a problem when I try to use the inline edit feature. Here is my code:
My First Grid
<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<style type="text/css">
html, body {
margin: 0;
padding: 0;
font-size: 75%;
}
</style>
<script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var lastsel2
$("#list").jqGrid({
url:'example.php',
datatype: 'xml',
mtype: 'GET',
colNames:['id','name', 'status'],
colModel :[
{name:'id', index:'id', width:55},
{name:'name', index:'name', width:90, editable: true},
{name:'status', index:'status', width:80, align:'right', editable: true},
],
onSelectRow: function(id){
if(appid && appid!==lastsel2){
jQuery('#list').restoreRow(lastsel2);
jQuery('#list').editRow(id,true);
lastsel2=id;
}
},
editurl: "example.php",
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'appid',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'My first grid'
});
});
</script>
</head>
<body>
<table id="list"><tr><td/></tr></table>
<div id="pager"></div>
</body>
The problem is it could edit the row when I click it, and also can save temporarily after I press the enter. But when I reload the grid, it still shows the previous data before I eidt, which means it doesn't update the database. I wonder why and how to solve it?
Here is the example.php code:
<?php
include("dbconfig.php");
$page = $_GET['page'];
$limit = $_GET['rows'];
$sidx = $_GET['sidx'];
$sord = $_GET['sord'];
if (!$sidx)
$sidx = 1;
$db = mysql_connect("$dbhost", "$dbuser", "$dbpassword") or die("Connection Error: " . mysql_error());
mysql_select_db("$database") or die("Error connecting to db.");
$result = mysql_query("SELECT COUNT(*) AS count FROM app");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $row['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;
$SQL = "SELECT id, name, status FROM app";
$result = mysql_query($SQL) or die("Couldn't execute query." . mysql_error());
header("Content-type: text/xml;charset=utf-8");
$s = "<?xml version='1.0' encoding='utf-8'?>";
$s .= "<rows>";
$s .= "<page>" . $page . "</page>";
$s .= "<total>" . $total_pages . "</total>";
$s .= "<records>" . $count . "</records>";
// be sure to put text data in CDATA
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$s .= "<row id='" . $row['id'] . "'>";
$s .= "<cell>" . $row['id'] . "</cell>";
$s .= "<cell>" . $row['name'] . "</cell>";
$s .= "<cell>" . $row['status'] . "</cell>";
$s .= "</row>";
}
$s .= "</rows>";
echo $s;
?>
First of all you should change the code
onSelectRow: function(id){
if(appid && appid!==lastsel2){
jQuery('#list').restoreRow(lastsel2);
jQuery('#list').editRow(id,true);
lastsel2=id;
}
}
to something like
onSelectRow: function (id) {
if (id && id !== lastsel2){
jQuery('#list').restoreRow(lastsel2);
jQuery('#list').editRow(id,true);
lastsel2 = id;
}
}
because currently you use undefined appid instead of id.
Moreover you should remove trailing comma at the end of colModel definition: change },] to }] and place semicolon after var lastsel2.