How to populate mysql db details using Extjs grid in php? - php

First in php page I am getting mysql db details and display in console, but I need to populate db details in ExtJs grid.
Can you help me how to write ExtJs grid with php and how to populate db details .
<?php
// Install the DB module using 'pear install DB'
require_once( "db.php" );
$data = array();
$db =& DB::connect("mysql://root#localhost/praveen", array());
if (PEAR::isError($db)) { die($db->getMessage()); }
$res = $db->query( "SELECT * FROM users " );
?>
<html>
<link rel="stylesheet" type="text/css" href ="http://localhost:8080/ext/ext-4.2.1.883/resources/css/ext-all.css"/>
<script type = "text/javascript" src = "http://localhost:8080/ext/ext-4.2.1.883/ext-all-dev.js"/>
<script type="text/javascript">
Ext.onReady(function(){
//how to get the populate db details in grid here !
});
</script>
<body>
<table>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Nmae</th>
</tr>
<?php while( $res->fetchInto( $row,
DB_FETCHMODE_ASSOC ) ) { ?>
<tr>
<td><?php echo( $row['firstname'] ); ?></td>
<td><?php echo( $row['middlename'] ); ?></td>
<td><?php echo( $row['lastname'] ); ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>

You first need to create a store, I'd prefer a JsonStore, then you'd need to populate it using ajax.
your code should be some what like this:
var store = new Ext.data.JsonStore(
{
proxy: new Ext.data.HttpProxy({url: 'url to your php script to fetch data from the DB',
method:'GET'}),
root:'root of the JSON string in which data resides.',
fields: ['list of fields'],
});
store.load();
after that you need to create the column model of the grid, this is the sample column model from one of my projects.
var colModel = new Ext.grid.ColumnModel([checkboxsel{header:'UserName',dataIndex:'USERNAME',sortable:true}
{header:'Name',dataIndex:'NAME',sortable:true,editor:textFieldEditor}, {id:'DOB',header:'Date of Birth',dataIndex:'DATEOFBIRTH',sortable:true,editor:dateFieldEditor},
{header: 'Password', dataIndex: 'PASSWORD',editor:passwordFieldEditor}
]);
next you need to create a gridView and a GridPanel
var gridView = new Ext.grid.GridView();
var grid = new Ext.grid.EditorGridPanel
({
title:'My First Grid',
id:'myFirstGrid',
renderTo: Ext.get('id of your html element in which you want the grid to be displayed'),
autoHeight: true,
store:store,
,
width:600,
loadMask:true,
colModel:colModel,
sm:checkboxsel,
});

Related

Error in Retrieving data using Ajax Call

I have a problem with getJSON. Following is the scenario -
Here is my HTML code -
<h3 align="center"> Example 1</h3>
<table align="center">
<tr>
<td><select name="stud_sel" onChange="getDetails(this)">
<option value="100">Lohith</option>
<option value="101">Ranjeet</option>
<option value="102">Karthik</option>
<option value="103">Pav</option>
</select></td>
</tr>
</table>
<br/>
<!--HERE WRITE THE RESPONSE DATA -->
<div id ="stud_tbl" align="center"> </div>
<!---END-->
Here is my Javascript function ---->
function getDetails(id) {
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
var id_val = id.value;
//window.alert(id_val);
var url = "http://localhost:81/json-with-jquery/json.php?id="+id_val;
alert (url);
$.getJSON(url, function(json) {
$.each(json, function(i,v) {
myTable += "<tr><td>"+i+"</td><td>"+v+"</td></tr></table>";
});
$("#stud_tb1").html(myTable) ;
});
};
And the PHP file from where data is coming to my JS function is -
<?php
include 'configure.php';
$stud_id = $_GET['id'];
echo $_GET['id'];
$qr = "SELECT * FROM student_details WHERE regno = $stud_id";
$res= mysql_query($qr);
$row = mysql_fetch_array($res);
$stud_arr["full_name"] = $row["full_name"];
$stud_arr["reg_no"] = $row["regno"];
$stud_arr["address"] = $row["address"];
$stud_arr["mark1"] = $row["mark1"];
$stud_arr["mark2"]= $row["mark2"];
$stud_arr["mark3"] = $row["mark3"];
header('Content-type: application/json');
echo json_encode($stud_arr);
?>
The problem here is when I run my PHP file individually, it's giving me the expected data in JSON format, with the help of json_encode($stud_array).
The same when I am trying to display on my HTML page, I don't receive any data on the page.
The "alert(url)" in my JS function is properly alerting message as "http://localhost:81/json-with-jquery/json.php?id=102" when I selected the list item with ID 102.
Am not sure why the data is not being displayed. I hope I have the Javascript written properly. Please help.
Populate your table properly,
myTable="<table>";
$.each(json, function(i,v) {
myTable += "<tr><td>"+i+"</td><td>"+v+"</td></tr>";
});
myTable+="</table>";
Your output is not valid json that's the problem, your echo $_GET['id']; is breaking your json output, remove it. If you want to send it in the output put it in the json response.
$stud_arr["id"] = $_GET['id'];
header('Content-type: application/json');
echo json_encode($stud_arr);

Update stock price using ajax

I am doing a small personal web portfolio in order to learn web development. I have a list of all the stocks that I have "bought" and I would like to update the price in real-time from yahoo finance. I can already do the price update but I override the table that I display the stocks with a new one that is called using javascript.
I know there must be a cleaner way. I am trying to update the price using javascript but I don't think I am doing everything right.
Here is what I have so far.
Portfolio.php displays all the stocks I have
<?php foreach ($shares as $row): ?>
<tr >
<td><?php echo $row["symbol"];?></td>
<td><?php echo $row["name"];?></td>
<td style="text-align: right;"><?php echo $row["shares"];?></td>
<td id="price" style="text-align: right;">$ <?php echo number_format($row["price"],2);?></td>
<td style="text-align: right;"><?php
$change = number_format($row["change"],2);
echo sprintf( "%+1.2f", $change );
echo " ( ";
echo $row["pct"];
echo " )";
?></td>
<td style="text-align: right;">$ <?php echo $row["dayGain"];?></td>
<td style="text-align: right;">$ <?php echo number_format($row["total"],2);?></td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript" src="../html/js/update.js" ></script>
Then I have update.php which returns all the stock information from yahoo finance as a json
<?php
// configuration
require("../includes/config.php");
//query user's portfolio
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = array();
//for each of the user info
foreach($rows as $row){
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";
$yql_query = "select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22".$row['symbol']."%22)%0A%09%09";
$env = "env=http%3A%2F%2Fdatatables.org%2Falltables.env";
$yql_full_query = $yql_base_url . "?q=" . $yql_query . "&format=json&" . $env;
$session = curl_init($yql_full_query);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
$stock = json_decode($json);
if($stock->query->results !== false){
$shares [] = array(
"symbol" => $stock->query->results->quote->symbol,
"price" => $stock->query->results->quote->LastTradePriceOnly
);
}
}
$return = array("price" => $shares );
echo json_encode($return);
?>
And the third file is update.js in which I am trying to have javascript
$(document).ready(function(){
function stock() {
$(function() {
$.getJSON('../update.php',function(result){
$("div#price2").html(result.price);
});
});
stock();
setInterval(stock(), 10000);
});
});
If I go directly to update.php I can view the prices as json. I think the problem lies with the update.js file but I cannot figure out what the problem is. I cannot even print Hello from update.js in the price field.
What I am trying to do is display the stocks that I have stored in the database and then update the price using ajax and javascript. Any help would be appreciated. Thanks in advance.
Use php's json functions coupled with a .getJSON to update it... Here's some example code:
// pull_stock_price.php
<?php
$return = array("content" => "New Stock Price: $2000");
json_encode($return);
?>
// Jquery to pull stock price once every 10 seconds:
function stock() {
$(function() {$.getJSON("pull_stock_price.php",function(result){
$("#StockPrice").html(result.content);
});
});
stock();
setInterval(stock, 10000);
// HTML!
<td><div id="StockPrice"></div></td>
What this does: Every 10 seconds the user's browser will pull pull_stock_price.php and will take the content provided from the json and update . You can have pull_stock_price.php pull from the database, curl or really anywhere and format the data how you want it.

Issue with accessing a value from a table with jquery

Hey guys I am trying to get a specific name from a table. Here is my code:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
var notes_name = $(this).document.getElementById("#user_table");
alert(notes_name);
run();
});
});
Here is the above this is where I am trying to access the associated username with which table row was click with the #notesAccessor
Table:
.........
<td>
$csvusername
</td>
.........
<td>
";
if ($checkNotes[1] == 'No')
{
echo "None";
}
if ($checkNotes[1] == 'Yes')
{
echo "<a href='#' id='NotesAccessor'>Click to access</a>";
}
echo "
</td>
........
My question is - how do I get the $csvusername of the associated NotesAccessor so I can then send this to a dialog in Jquery and open of the notes of that one person I need to get.
Hope this makes sense.
update:
here is full table:
<table class='results'>
<tr class='firsttr' style='background:gray;'>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone</td>
<td>Username</td>
<td>Password</td>
<td>Status</td>
<td>Combined Single Limit</td>
<td>Bodily Injury Each Person</td>
<td>Bodily Injury Each Accident</td>
<td>Property Damage</td>
<td>Address</td>
<td>Notes</td>
<td>#</td>
</tr>"; $j = 0; while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { $val = 1; $csvfirst
= $row; $csvfirstname = $csvfirst['firstname']; $csvlastname = $csvfirst['lastname'];
$csvemail = $csvfirst['email']; $csvphone = $csvfirst['phone']; $csvusername
= $csvfirst['username']; $csvpassword= $csvfirst['password']; $csvstatus
= $csvfirst['status']; $csvnotes = $csvfirst['notes']; $csl = $csvfirst['Combinedlimit'];
$bodyinj = $csvfirst['bodyinjur']; $eachacc = $csvfirst['bodyinjureachacc'];
$propertydmg = $csvfirst['propertydmg']; // Select the current employees
address $psql = "SELECT MailingAdrs FROM insuranceverificationdisclaimer
WHERE TraineeUsername =:user"; $psth= $DBH->prepare($psql); $psth->execute(array(':user'
=> $csvusername )); while ($prow = $psth->fetch(PDO::FETCH_ASSOC)) { $pcheck
= $prow; $address = $pcheck['MailingAdrs']; } if ($csvstatus != "No Longer
Work Here" && $csvstatus == "Confirmed"){ //check to see if notes exist
if (empty($csvnotes)) { $checkNotes = 0; } else { $checkNotes = 1; } $memberfirstnamearray[$j]
= $csvfirstname; $memberlastnamearray[$j] = $csvlastname; $memberemailarray[$j]
= $csvemail; $memberphonearray[$j] = $csvphone; $membercsl[$j] = $csl;
$memberbodyinj[$j] = $bodyinj; $membereachacc[$j] = $eachacc; $memberpropertydmg[$j]
= $propertydmg; $memberstatus[$j] = $csvstatus; $memberaddress[$j] = $address;
$j++; $i++; echo "
<tr>
<td>$csvfirstname</td>
<td>$csvlastname</td>
<td>$csvemail</td>
<td>$csvphone</td>
<td class='user_table'>$csvusername</td>
<td>$csvpassword</td>
<td>$csvstatus</td>
<td>$csl</td>
<td>$bodyinj</td>
<td>$eachacc</td>
<td>$propertydmg</td>
<td>$address</td>
<td>"; if ($checkNotes == 0) { echo "None"; } if ($checkNotes == 1) { echo
"<a href='#' id='NotesAccessor'>Click to access</a>"; } echo "</td>
<td>$i</td>
</tr>"; } }
</table>
You are mixing pure JavaScript with jQuery, you can solve it as follows.
First of all, you can put a class to identify the <td> with $csvusername, like class='td_with_csvusername' and then do this:
$(document).ready(function () {
$(".NotesAccessor").on("click", function () {
var td = $(this).parent().parent().find(".td_with_csvusername");
alert(td.html());
});
});
Posting the output HTML is better than the PhP version but I assume you have HTML similar to this:
<table>
<tbody>
<tr>
<td>UserName</td>
<td><a href='#' id='NotesAccessor'>Click to access</a>"</td>
</tr>
</tbody>
</table>
Then you can look for the previous sibling of the parent of the anchor by using jQuery's parent() and prev(), similar to this:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
var notes_name = $(this).parent().prev().html();
alert(notes_name);
//run();
});
});
DEMO - Looking to the matching username column
If the above HTML is not like that then please post the exact output as it is important for knowing how to traverse to the matching td in the same tr when you click the anchor. Assuming that is what you are trying to achieve.
Edit
Only seen your update now. I know you already have a solution but for completeness I have added to this answer anyway in case it is useful to future users.
In your sample code you already have class on the user-name cell user_table. You can use that to target instead then. Also, given you said you will have several rows with the #NoteAccessor, you should change the id="NoteAccessor" to class="NoteAccessor" as ids have to be unique or it is invalid HTML. In addition jQuery only returns the first element with a matched id.
The script which you end up with is straight forward then using parent() as before but now you can also use prevAll() specifying the class selector:
$(document).ready(function () {
// using class ".NotesAccessor" instead of id "#NotesAccessor"
// as element is repeated in each tr
$(".NotesAccessor").click(function () {
var notes_name = $(this).parent().prevAll('.user_table').html();
alert(notes_name);
});
});
DEMO - Using parent() and prevAll('.user_table')

Cakephp ajax delete with j query

i've found this http://www.jamesfairhurst.co.uk/posts/view/ajax_delete_with_cakephp_and_jquery/ tutorial on the web, but it was for cakephp 1.3.
After making some adjustements to it , i try to run it, but something is going wrong. While the record gets deleted(as it should be), it refreshed the page. It's like Ajax and Jquery are not working.
Below is my code
The Controller Action
function delete($id=null) {
// set default class & message for setFlash
$class = 'flash_failure';
$msg = 'Invalid User Id';
// check id is valid
if($id!=null && is_numeric($id)) {
// get the Item
$item = $this->User->read(null,$id);
// check Item is valid
if(!empty($item)) {
$user = $this->Session->read('Auth.User');
// $exists=$this->User->find('count',array('conditions'=>array("User.username" => $user)));
if($item['User']['username']==$user['username']){
$msg = 'You cannot delete yourself!';
}
// try deleting the item
else if($this->User->delete($id)) {
$class = 'flash_success';
$msg = 'User was successfully deleted';
} else {
$msg = 'There was a problem deleting User, please try again';
}
}
}
// output JSON on AJAX request
if(/*$this->RequestHandler->isAjax()*/$this->request->is('ajax')) {
$this->autoRender = $this->layout = false;
echo json_encode(array('success'=>($class=='flash_failure') ? FALSE : TRUE,'msg'=>"<p id='flashMessage' class='{$class}'>{$msg}</p>"));
exit;
}
// set flash message & redirect
$this->Session->setFlash($msg,$class,array('class'=>$class));
$this->redirect(array('action'=>'manage'));
}
The View
<?php //view/users/manage.ctp ?>
<h1 class="ico_mug">Users</h1>
<?php echo 'Add User '.$this->Html->link($this->Html->image("add.jpg"), array('action' => 'register'), array('escape' => false));//print_r ($users); ?>
</br>
<table id="table">
<tr>
<th>ID</th>
<th>Username</th>
<th>Last Login</th>
<th>Options</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($users as $rs): ?>
<tr>
<?php echo $this->Html->script('jquery'); ?>
<td class="record">
<?php echo $rs['User']['id']; ?>
</td>
<td class="record"><?php echo $rs['User']['username']; ?></td>
<td class="record"><?php if(!$rs['User']['last_login']) {echo "Never Logged In";} else {echo $rs['User']['last_login'];} ?></td>
<td class="record"> <?php echo $this->Html->link($this->Html->image("edit.jpg"), array('action' => 'edit',$rs['User']['id']), array('escape' => false));?>
<?php
$user = $this->Session->read('Auth.User');
if($rs['User']['username']!=$user['username'])
echo $this->Html->link($this->Html->image("cancel.jpg"), array('action' => 'delete',$rs['User']['id']), array('escape' => false),array('class'=>'confirm_delete'));?>
<?php
if($rs['User']['username']!=$user['username'])
// simple HTML link with a class of 'confirm_delete'
echo $this->Js->link('Delete',array('action'=>'delete',$rs['User']['id']),array('escape' => false),array('class'=>'confirm_delete'));
?></td>
</tr>
<?php endforeach; ?>
<div class="paging">
<?php echo $this->Paginator->prev('<< ' . __('previous'), array(), null, array('class'=>'disabled'));?>
| <?php echo $this->Paginator->numbers();?>
| <?php echo $this->Paginator->next(__('next') . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
</table>
<div id='ajax_loader'></div>
The Jquery
// on dom ready
$(document).ready(function(){
// class exists
if($('.confirm_delete').length) {
// add click handler
$('.confirm_delete').click(function(){
// ask for confirmation
var result = confirm('Are you sure you want to delete this?');
// show loading image
$('.ajax_loader').show();
$('#flashMessage').fadeOut();
// get parent row
var row = $(this).parents('tr');
// do ajax request
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
// hide loading image
$('.ajax_loader').hide();
// hide table row on success
if(response.success == true) {
row.fadeOut();
}
// show respsonse message
if( response.msg ) {
$('#ajax_msg').html( response.msg ).show();
} else {
$('#ajax_msg').html( "<p id='flashMessage' class='flash_bad'>An unexpected error has occured, please refresh and try again</p>" ).show();
}
}
});
}
return false;
});
}
});
Please take in mind that i'm very new to all this Jquery and Ajax thing, as well as in cakephp.
What is causing that behaviour ? (also if i try to remove the redire from the controller, i get a message that "view delete was not found" )
First of all check cookbook for HtmlHelper::link and JsHelper::link. Not sure what version of cake you have, so just switch to the right one.
The thing is - none of your Delete links has class confirm_delete (use firebug or some debugging tool) - so the link gets clicked but the javascript is never executed, that's why you get redirected.
In your case it would be:
echo $this->Html->link($this->Html->image('cancel.png'), array('controller' => 'users', 'action' => 'delete', $rs['User']['id']), array('escape'=>false, 'class'=>'confirm_delete') );
and
echo $this->Js->link('Delete', array('controller' => 'users', 'action'=>'delete', $rs['User']['id']), array('escape' => false, 'class'=>'confirm_delete'));
Then I see $('.ajax_loader').hide(); but in your view is element with id="ajax_loader", so the selector should be $('#ajax_loader').hide();
Same with $('#ajax_msg').html(, double check you have that element on page with the id="ajax_msg"
Hope it helps you further;)

Auto populate based on dropdown selected, need help

How can I auto populate the data from db by dropdown selected?
and my dropdown result already appear as well, the code as following:
<?php
echo '<tr>
<td>'.$customer.'</td>
<td><select name="customer_id">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
and the result of dropdown above listed as
admin
customer1
FREE
loaded from following db
INSERT INTO `my_customer` (`customer_id`, `name`, `firstname`, `lastname`) VALUES
(8, 'admin', '', ''),
(6, 'customer1', 'ok', ''),
(7, 'FREE', 'marj', 'om');
so whenever dropdown selected i want the all data below:
<tr>
<td><?php echo $firstname; ?></td>
<td><?php echo $lastname; ?></td>
</tr>
also auto populate, it seem need javascript/ajax/jquery to fixed it, I was Wondering if someone could help me, and thanks in advance
Addtion JSON CALL
I have the json call already as following:
(let say this placed at customer.php with url index.php?p=page/customer)
public function customers() {
$this->load->model('account/customer');
if (isset($this->request->get['customer_id'])) {
$customer_id = $this->request->get['customer_id'];
} else {
$customer_id = 0;
}
$customer_data = array();
$results = $this->account_customer->getCustomer($customer_id);
foreach ($results as $result) {
$customer_data[] = array(
'customer_id' => $result['customer_id'],
'name' => $result['name'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname']
);
}
$this->load->library('json');
$this->response->setOutput(Json::encode($customer_data));
}
and the db
public function getCustomer($customer_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
return $query->row;
}
Suppose You are using jQuery, You will listen to select change event and then do an ajax call for PHP function that will return the data. The data will then be outputed to the appropriate places. I advise to set id attributes for next tags: <select>, <td> for name, <td> for surname, like so:
<select name="customer_id" id="customer_id>...</select>
<td id="firstname"> echo firstname </td>
<td id="lastname"> echo lastname </td>
Then the jquery code:
<script type="text/javascript">//<!--
$(document).ready(function(){
$('select#customer_id').change(function(){
$.post(
"http://www.domain.com/my_php_script.php",
{customer_id: $(this).val()},
function(data){
$('td#firstname').html(data.firstname);
$('td#lastname').html(data.lastname);
}
);
});
});
//--></script>
Supposing that Your my_php_script.php retrieves the data from database by given customer_id in $_POST['customer_id'] and returns a JSON object like echo json_encode(array('firstname' => FIRSTNAME_FROM_QUERY, 'lastname' => LASTNAME_FROM_QUERY));
ADDITION:
There are two options how to solve it - in JS instead of
$.post()
You have to use
$.get(...)
OR in Your PHP script instead of
$this->request->get['customer_id']
You have to use
$this->request->post['customer_id']
at every place... This should do it...
E.g.:
<script type="text/javascript">//<!--
$(document).ready(function(){
$('select#customer_id').change(function(){
$.get(
"http://www.domain.com/my_php_script.php",
{customer_id: $(this).val()},
function(data){
$('td#firstname').html(data.firstname);
$('td#lastname').html(data.lastname);
}
);
});
});
//--></script>

Categories