I'm kinda rookie in this, but I need help with Google Gauge that should take latest entry in database and display it, while updating automatically without the need to reload the site. Right now I have code that displays it, but for it to update to new values I need to reload the page.
Here's what I have so far:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['ProductPurity', <?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ProductPurity"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?> ],
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
setInterval(function() {
data.setValue(0 ,1 , <?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ProductPurity"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
);
chart.draw(data, options);
}, 5000);
setInterval(function() {
data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
chart.draw(data, options);
}, 5000);
setInterval(function() {
data.setValue(2, 1, 60 + Math.round(20 * Math.random()));
chart.draw(data, options);
}, 26000);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>
php runs on the server, so it is only going to run once per page load.
to update the chart without reloading the page,
you will need to separate the php from the html / javascript.
save the php to a different file, all by itself.
you need to include the rest of the data in the php,
including the column headings.
see following snippet for the php.
for example purposes, we'll name the file --> getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
next, save the html / javascript to its own file.
for example purposes, we'll name the file --> chart.html
to get the data from php,
we'll use jquery ajax.
see following snippet...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>
EDIT
need to make sure the Value column...
is a number --> 99.9594
not a string --> "99.9594"
you can convert using --> (float)
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
and / or use the JSON_NUMERIC_CHECK constant on the encode statement...
echo json_encode($data, JSON_NUMERIC_CHECK);
Related
we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
once we got success response we are displaying alert message....
Requirement :
but now i want to display Progress like "1% completed , 2 % completed" , so on.... :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function()
{
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax
({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response)
{
response = $.parseJSON(response);
alert("completed");
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
Please try this script and code
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function(){
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var count = selected.length
var perPlush = 100/count;
var per = 0;
for (var i = 0; i <= count; i++) {
$.ajax
({
type: "POST",
url: "api.php",
data: {id : selected[i]},
success: function(response)
{
response = $.parseJSON(response);
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
per = per + perPlush;
console.log(Math.round(per) + " % Complated");
$("#progress").html(Math.round(per) + " % Complated");
}
});
}
});
Your api.php file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_POST['id']; //960856092
$response = array();
$orderid = $id;
$hide = '';
$post_data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "http://plapi.ecomexpress.in/track_me/api/mawbd/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec ($ch);
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
if($orderResults){
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
else{
$response[$orderid] = ['status' => 'Order already placed'];
}
echo json_encode($response);
?>
i have written code in controller to move the uploaded file to folder ,but it was not working ,my code is
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a, '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
i think this line 'if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){ ... } was not working ,through this code i am able to store the '0 in my database i.e else part of the code.
how to move the uploaded image to folder and path to my database field..plz help me any one...!
my script code is
function addAdminList(){
var branchId = $('#branchId').val();
var branchName = $('#branchName').val();
var curiculumName = $('#curiculumName').val();
var owner = $('#owner').val();
var startdate = $('#startdate').val();
var phone = $('#phone').val();
var desc = $('#desc').val();
var address = $('#address').val();
var timings = $('#timings').val();
var image = $('#image').val();
if(!$("#addClsGrpFrm").validationEngine('validate')){
return false;
}
$('.overlay').show();
$.ajax({
url : '<?php echo BASE_PATH; ?>adminAjax/addAdminList',
type : 'POST',
data : {
branchId : branchId,
branchName : branchName,
curiculumName : curiculumName,
owner : owner,
startdate : startdate,
phone : phone,
desc : desc,
address : address,
timings : timings,
image : image
},
success : function(res){
$('.overlay').hide();
if(res == 0){
}
parent.$.colorbox.close();
oTable.fnDraw();
return false;
},
error : function(res){
alert('Server Error Occurred');
}
});
}
my form is
<form id="addClsGrpFrm" method="post" action="#" onsubmit="return disableFrmSubmit()">
<div class="flash_msg"><?php echo $this->Session->flash(); ?></div>
<input type="hidden" name="data[branch][id]" readonly id="branchId" value="0">
<div class="login-form">
<label>Shop Image</label>
<input type="file" id="image" data-prompt-position="topLeft:200" name="data[branch][image]" placeholder="" class="validate[required]" />
.....
</div>
<div class="login-form">
<input type="button" onclick="addAdminList()" class="login-btn" value="Submit">
</div>
<div class="clear"></div>
</form>
Some suggestions while submitting your form :
Use FormData when submitting your form rather than appending them one by one.
The extension extraction process that you are using in your controller may not save some files with "." in their filename.
I have created a test form for your knowledge.This is the form:
<form id="testForm" method="post" action="<?php echo 'http://localhost/blog/users/test'; ?>">
<input type="file" name="image" id="image">
<input type="submit" value="Submit">
</form>
You can use FormData like so:
$('#testForm').on('submit', function(event) {
event.preventDefault();
var form_data = new FormData($(this)[0]); // this will get all your form's inputs
$.ajax({
url:"<?php echo 'http://localhost/blog/users/test.json'; ?>", // you can use your form action URL here
type:'POST',
data:form_data,
processData: false,
contentType: false
});
});
and finally in your controller:
public function test() {
if ($this->request->is('post')) {
if (!empty($this->request->data['image']['tmp_name']) && is_uploaded_file($this->request->data['image']['tmp_name'])) {
$filename = basename($this->request->data['image']['name']);
$imagePath = WWW_ROOT . DS . 'documents' . DS . $filename; // save the file where you wish
move_uploaded_file(
$this->request->data['image']['tmp_name'],
$imagePath // save $imagePath in your database
);
}
}
}
You can use $imagePath to save in your database and as for your file extension process you can use this function as it will get the filetype even if the filename has a "dot" in it :
public function findFileTypeAndName($filename)
{
$split_point = '.';
$parts = explode($split_point, $filename);
$last = array_pop($parts);
$fileNameAndType = array(implode($split_point, $parts), $last);
return $fileNameAndType;
}
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a['tmp_name'], WWW_ROOT . '/img/uploads/users/' . basename($a['name']))){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
The issue is just that you tried to pass the image array to strrchr($a) instead of strrchr($a['name']) at this point:
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
Then you also tried to pass $a which is an array into move_uploaded_file($a,...).
Check my corrections for that part of the code...
For an action in my controller that needs no view, I'm disabling the layout and template like this:
$this->autoRender = false;
And it's all good. However, in that same action I'm echoing a 'pass' or 'fail' to signal my view of the result. The problem is a bunch of text is also echoed: (my 'fail' or 'pass' at the very end)
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
</body>
</html>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head> ....
This is echoed 8 o 9 times.
How can I get rid of that so only my 'pass' or 'fail' are echoed?
Can you help?
I've tried
$this->layout = false; and
$this->render(false);
Thank you so much.
Update:**
Just noted it also echoes a bunch of javascrip code out of nowhere, (Removed < for pasting here) e.g.: pre class="cake-error" a href="javascript:void(0);" onclick="document.getElementById('cakeErr5035af14add0c-trace').style.display = (document.getElemen..
This is the whole action **
//This action is called via:
//mysite/qcas/loadProdFromFile/dirId:76
// or
//mysite/qcas/loadProdFromFile/dirId:76/filePath:J:\ep12219 - Air Pollution\Load\prodValues.csv
function loadProdFromFile() {
$this->autoRender = false;
// here we get dir info based on first (and perhaps sole) param received: dirId
$dirName = $this->Qca->Dir->find('first', array(
'recursive' => 0,
'fields' => array('Dir.name'),
'conditions' => array('Dir.id' => $this->request->params['named']['dirId']),
)
);
//if used did not provide filePath param, we use a default location based on dir info
if ((is_null($this->request->params['named']['filePath']))) {
$basedir = '/disk/main/jobs/';
$dirs = scandir($basedir);
$found = 0;
foreach ($dirs as $key => $value) {
if (strpos($value, $dirName['Dir']['name']) > -1) {
$found = 1;
break;
}
}
if (!$found) {
echo 'failfile';
exit;
}
$loadDir = '/disk/main/jobs/' . $value . '/Load/';
$thefiles = glob($loadDir . "*.csv");
$prodFile = $thefiles[0];
} else {
// if user provided a path, we build a unix path
// for some reason the extension is not posted, so we append it: only csv can be processed anyways
$prodFile = AppController::BuildDirsFile($this->request->params['named']['filePath']) . ".csv";
}
// we get here with a working file path
$fileHandle = fopen($prodFile, 'r');
if ($fileHandle) {
// start processing file to build $prodata array for saving to db
$counter = 0;
while (!feof($fileHandle)) {
$line = fgets($fileHandle);
if (strlen($line) == 0) {
break;
}
$values = explode(',', $line);
$prodata[$counter]['dir_id'] = $this->request->params['named']['dirId'];
$prodata[$counter]['name'] = $dirName['Dir']['name'];
$prodata[$counter]['employee_id'] = $values[1];
$a = strptime($values[0], '%m/%d/%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon'] + 1, $a['tm_mday'], $a['tm_year'] + 1900);
$prodata[$counter]['qca_start'] = $timestamp;
$end = $timestamp + ($values[2] * 60);
$prodata[$counter]['qca_end'] = $end;
$prodata[$counter]['qca_tipcode'] = $values[3] * -1;
$prodata[$counter]['qca_durint'] = 0;
$prodata[$counter]['qca_durtel '] = 0;
$prodata[$counter]['qca_durend'] = 0;
$prodata[$counter]['qca_signal'] = 0;
$prodata[$counter]['qca_restart'] = 0;
$prodata[$counter]['qca_stop'] = 0;
$prodata[$counter]['qca_prevtipc'] = 0;
$prodata[$counter]['qca_respid'] = 0;
$prodata[$counter]['qca_lastq'] = 0;
$prodata[$counter]['qca_smskey'] = 0;
$prodata[$counter]['qca_telconta'] = 0;
$prodata[$counter]['qca_execuqoc'] = 0;
$counter++;
}
} else {
// file was just no good
echo 'fail';
exit;
}
if (count($prodata) > 0) {
$this->Qca->saveMany($prodata);
echo count($prodata);
}
}
First of all I will paste here a fragment from cakeapi under http://api.cakephp.org/class/controller about how autoRender works:
autoRender boolean
Set to true to automatically render the view after action logic.
So this:
$this->autoRender = false ;
will generally turns off rendering the view but just after action logic is done. So thats why you get the echos from your action logic. You can whether remove your echo's from your code to prevent showing them or try this schema,
if something is wrong:
$this->Session->setFlash('Error');
$this->redirect(array('action' => 'your_error_page'));
which will move you to ur error page with Error string as a Flash text, or when its all fine:
$this->Session->setFlash('Its fine dude!');
$this->redirect(array('action' => 'your_ok_page'));
I have a problem with TCPDF:
viewPDF:
function viewPdf($id = null)
{
if (!$id)
{
$this->Session->setFlash('Sorry, there was no property ID submitted.');
$this->redirect(array('action'=>'index'), null, true);
}
Configure::write('debug',0); // Otherwise we cannot use this method while developing
$id = intval($id);
$property = $this->__view($id); // here the data is pulled from the database and set for the view
if (empty($property))
{
$this->Session->setFlash('Sorry, there is no property with the submitted ID.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}
__view:
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$this->set('calculation', $this->Calculation->read(null, $id));
}
viewPDF.ctp:
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed
than 'dejavusans'
$tcpdf->SetAuthor("KBS Homes & Properties a http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',20));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'Test';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All
rights reserved.';
// Now you position and print your page content
// example:
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
$tcpdf->Output('filename.pdf', 'I');
?>
PDF layout for CakePHP 2.2 ($content_for_layout is depricated):
<?php
header("Content-type: application/pdf");
echo $this->fetch('content');
?>
xtcpdf.php in app/Vendor:
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/**
* Overwrites the default header
* set the text in the view using
* $fpdf->xheadertext = 'YOUR ORGANIZATION';
* set the fill color in the view using
* $fpdf->xheadercolor = array(0,0,100); (r, g, b)
* set the font in the view using
* $fpdf->setHeaderFont(array('YourFont','',fontsize));
*/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
/**
* Overwrites the default footer
* set the text in the view using
* $fpdf->xfootertext = 'Copyright © %d YOUR ORGANIZATION. All rights reserved.';
*/
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>
And I always get "Sorry, there is no property with the submitted ID." and I don't see the problem.
you should have a look on this code :
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$data = $this->Calculation->read(null, $id));
return $data;
}
I am trying to implement jqgrid v3.7 in my webapplication created using cakephp v1.3.
My controller code is as follows
function admin_index()
{
// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $this->params['url']['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $this->params['url']['sidx'];
// sorting order - at first time sortorder
$sord = $this->params['url']['sord'];
// if we not pass at first time index use the first column for the index or what you want
if( !$sidx ) $sidx = 1;
// calculate the number of rows for the query. We need this for paging the result
$row = $this->Constituency->find('count');
$count = $row;
// calculate the total pages for the query
if( $count > 0 )
{
$total_pages = ceil($count / $limit);
}
else
{
$total_pages = 0;
}
// if for some reasons the requested page is greater than the total
// set the requested page to total page
if( $page > $total_pages ) $page = $total_pages;
// calculate the starting position of the rows
$start = $limit * $page - $limit;
// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if( $start < 0 ) $start = 0;
// the actual query for the grid data
$limit_range = $start . "," . $limit;
$sort_range = $sidx . " " . $sord;
//$result = $this->Constituency->findAll(null, "id,name", $sort_range, $limit_range, 1, null);
$this->Constituency->recursive = -1;
$result = $this->Constituency->find('all', array(
'fields' => array('id', 'name'),
'order' => $sidx,
'limit' => $start .",". $limit_range
));
$i=0;
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
foreach($result as $result)
{
$response->rows[$i]['id'] = $result['Constituency']['id'];
$responce->rows[$i]['cell']=array($result['Constituency']['id'],$result['Constituency']['name']);
$i++;
}
echo json_encode($response);
}
the view file contains the following code
$this->Html->css('ui.jqgrid');
$this->Html->script('jquery.jqGrid.min');
<script type="text/javascript">
$(document).ready(function(){
$("#list").jqGrid(
{
url:'<?php echo $this->Html->url(array("controller" => "constituencies", "action" => "index")); ?>',
datatype: "json",
colNames:['Id','Name'],
colModel:[
{name:'id',index:'id', width:55},
{name:'name',index:'name', width:90},
],
rowNum:10,
rowList:[10,20,30],
pager: jQuery('#pager'),
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption:"Constituencies"
});
$("#list").navGrid("#pager",{edit:false,add:false,del:false});
})
</script>
<div class="constituencies index">
<h2><?php __('Constituencies'); ?></h2>
<table id="list" class="scroll"></table>
<div id="pager" class="scroll" ></div>
</div>
Now when I load the index action I get a lot of errors
Undefined index: rows
Undefined index: sidx
Undefined index: sord
etc. etc.
Has anybody included jqgrid in a cakephp based application ?
How do I include the jqgrid in my application ?
Please help me do this.
Thanks
I don't use cakephp myself, but probably two links
http://www.trirand.com/blog/?page_id=393/help/integration-of-cakephp-and-jqgrid-tutorial/
and
http://www.trirand.com/blog/?page_id=393/help/how-to-integrate-jqgrid-with-cakephp/
can be helpful for you.
The errors you're getting look like PHP errors. Try putting a debug($this->params); statement at the top of your view file to see what the controller is spitting out.
There was some incorrect values assigned in the find function for constituency model.
here is the correct complete working code:
THIS IS THE CONTROLLER CODE:
1.) Leave the function in which the grid is shown a blank like this
function index()
{
}
2.) Then create a new function for showing the grid with data like this :
function admin_showGrid()
{
$this->autoRender = false;
// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $this->params['url']['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $this->params['url']['sidx'];
// sorting order - at first time sortorder
$sord = $this->params['url']['sord'];
$page = $this->params['url']['page'];
// if we not pass at first time index use the first column for the index or what you want
if( !$sidx ) $sidx = 1;
// calculate the number of rows for the query. We need this for paging the result
$row = $this->{Model_Name}->find('count');
$count = $row;
// calculate the total pages for the query
if( $count > 0 )
{
$total_pages = ceil($count / $limit);
}
else
{
$total_pages = 0;
}
// if for some reasons the requested page is greater than the total
// set the requested page to total page
if( $page > $total_pages ) $page = $total_pages;
// calculate the starting position of the rows
$start = $limit * $page - $limit;
// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if( $start < 0 ) $start = 0;
// the actual query for the grid data
$limit_range = $start . "," . $limit;
$sort_range = $sidx . " " . $sord;
//$result = $this->{Model_Name}->findAll(null, "id,name", $sort_range, $limit_range, 1, null);
$this->{Model_Name}->recursive = -1;
$result = $this->{Model_Name}->find('all', array(
'fields' => array('id', 'name'),
'order' => $sort_range,
'limit' => $limit_range
));
$i = 0;
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
foreach($result as $result)
{
$response->rows[$i]['id'] = $result['{Model_Name}']['id'];
$response->rows[$i]['cell'] = array($result['{Model_Name}']['id'], $result['{Model_Name}']['name']);
$i++;
}
echo json_encode($response);
//writing exit() is necessary.
exit();
}
THIS IS THE VIEW CODE:
1.) include the necessary files
echo $this->Html->css('ui.jqgrid');
echo $this->Html->script('grid.locale-en');
echo $this->Html->script('jquery.jqGrid.min');
2.) add the following javascript code in your VIEW file
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid(
/* '#list' is the ID of the table in which you want populated results */
{
url:'<?php echo $this->Html->url(array("controller" => "{Controller_Name}", "action" => "{Action_Name}")); ?>',
datatype: "json",
mtype: "GET",
colNames:['Id','Name'],
colModel:[
{name:'id',index:'id', width:55},
{name:'name',index:'name', width:90},
],
rowNum:10,
rowList:[10,20,30],
pager: jQuery('#pager'), /* id of the pagination element */
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption:"Enter table Heading or the name you want to show for the table",
height:"auto",
autowidth: true
});
jQuery("#list").navGrid("#pager",{edit:false,add:false,del:false});
})
</script>
3.) And finally the HTML in the same view file
<table id="list" style="height:auto;"></table>
<div id="pager"></div>
If you still face any problems with the code above let me know.