Update stock price using ajax - php

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.

Related

FPDF & While loop

I am currently working on an invoice script which currently pulls the information from MySql and then converts that information into a PDF and emails it using PHPmailer.
The part im stuck with is how I would convert this into a PDF. I would like to be able to post the orderid to a following page which then does the conversion to PDF.
I have attached my script below for some help.
<?php
session_start();
$username = $_SESSION['username'];
$con = mysqli_connect('***', '***', '***', '***');
if (!isset($con)) {
die("Connection to Aurora System failed.");
}
$orderid = $_POST['order_id'];
?>
<!doctype html>
<html>
<body class="body page-orderview clearfix">
<div class="element"></div>
<p class="text text-1">SMKD Field Force</p>
<img class="image" src="images/smkd_logo.png">
<p class="text text-2">Welcome</p>
<p class="text text-3">Order <?php echo "$orderid"; ?>
<table>
<tr>
<th>Product Title</th>
<th>Nicotine Strength</th>
<th>Quantity</th>
<th>Price (inc. VAT)</th>
</tr>
<?php
$query = "SELECT `product`, `variant`, `quantity` FROM orders_detail WHERE order_id = '$orderid'";
$result = mysqli_query($con, $query);
$quantitytotal = 0;
$quantityline = - 0;
while ($row = mysqli_fetch_assoc($result)) {
$product = $row['product'];
$stuff = $row['quantity'];
$variant = $row['variant'];
$linequantity = $stuff;
$quantitytotal += $stuff;
$pricequery = "SELECT product_price FROM products WHERE product_name = '$product'";
$priceresult = mysqli_query($con, $pricequery);
$pricetag = 0;
$priceline = 0;
while ($rowprice = mysqli_fetch_assoc($priceresult)) {
$price = $rowprice['product_price'];
$pricetag += $price;
$priceline = $price;
}
$linetotal = $priceline * $linequantity;
echo '<tr><td>' . $product .' </td> ' . '<td>' . $variant . '</td>' . ' <td> ' . $linequantity . '</td>' . '<td> £' . $linetotal . '</td> </tr>';
}
$total = $pricetag * $quantitytotal;
?>
<tr><td>Total Ex Vat:</td><td> Total Inc Vat:</td></tr>
<tr><td><?php echo "£" . ($total / 1.2);?></td>
<td><?php echo "£" . $total; ?></td></tr>
</table>
</p><br>
<form method="post" action"pdfinvoice.php">
<input type="hidden" value="<?php echo $orderid; ?>" name="orderid">
</form>
Submit button goes here
</body>
</html>
I wouuld not object to converting the entire page to a PDF but from what I understand this isn't possible with FPDF.
Regards & Many thanks!
As long as you don't make it too complex in regard to styling and html elements, I suggest taking a look at https://github.com/dompdf/dompdf, it's a pretty powerfull HTML to PDF converter library and is supports quite a lot of HTML.
Just forms and the like aren't going to work inside of the pdf, so don't include those (they may or may not be rendered, depends on the exact html tag.)
I actually just completed the same task a couple weeks ago. My page doesn't display the pdf however. Upon completion of checkout the page displays a success message and emails the pdf to the user.
Once you download and include the the FPDF library in your php file. Its just a matter of creating the FPDF object, adding to it, and outputting it.
require "Resources/PDF/fpdf.php";
$pdf = new FPDF();
$pdf->SetAutoPageBreak(true, 0);
$pdf->SetLeftMargin(8);
$pdf->AddPage();
$pdf->SetFont('Arial','B',20);
$pdf->SetTextColor(255);
$pdf->SetFillColor(0,153,204);
$pdf->Cell(194,10,'MyCompany Inc.','LRT',0,'L', true);
$pdf->Ln();
$pdf->SetFont('Arial','I',12);
$pdf->Cell(97,10,'Invoice #: '.$id.''.$cnt.'','LB',0,'L', true);
$pdf->Cell(97,10, "Date: ".date("d-m-Y")." ",'RB',0,'R', true);
$pdf->Ln();
$pdf->SetTextColor(0,153,204);
$pdf->SetFont('Arial','B',14);
$pdf->Cell(40,10,'Ship to:',0,4);
$pdf->SetTextColor(0,0,0);
$pdf->SetFont('Arial','I',12);
$pdf->Cell(40,5, $_POST['shippingName'],0,5);
$pdf->Cell(40,5, $COMP,0,6);
$pdf->Cell(40,5, $EMAIL,0,6);
$pdf->Cell(40,5, $_POST['shippingPhoneNumber'],0,7);
$pdf->Cell(40,5, $_POST['shippingAddress'],0,8);
$pdf->Cell(40,5, $_POST['shippingPostalCode'],0,9);
$pdf->Cell(40,5, $_POST['shippingCity'],0,10);
$pdf->Cell(40,5, $_POST['shippingProvince'],0,11);
$pdf->Cell(40,5, $_POST['shippingCountry'],0,12);
$pdf->Output(); //should display the pdf to the page
Output("filepath"); can save pdf to directory where you could then email the file.
The above will create a header and list User's info passed in through $_POST variables.
The FPDF documentation can be helpful at times. http://www.fpdf.org/

How to populate mysql db details using Extjs grid in 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,
});

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);

undefined ID in javascript when ID is passed from PHP variable

I've done some searches and I've come up with no clear answer. I'm not a javascript person at all and am pretty clueless. PHP I understand however, and to me this should work. I should also note, that this script used to use document.all for it's javascript, which I've tried to update to getElementById() when possible (since document.all was throwing an error in firebug).
Now for the most part, the page displays fine, albeit without the javascript changes that are supposed to happen.
I must also apologize for the archaic nature of the code, I inherited this code when I took over as internet guy for our gaming club. This code is for the purchase of fictional items using fictional credits.
When I click an item to "buy" it (or maybe not whichever) The background of that row is supposed to turn green, and the credits are supposed to be subtracted from my total account (or reverse if I uncheck the box). Clicking the submit button adds this stuff I clicked to another sheet, and subtracts the actual amount from my account.
Currently I get a "tr615 is undefined" error This is the PHP generated code for the element as shown below.
If someone can help me figure this out it would fantastic. I just can't seem to find an answer after a few days of searching google and here.
PHP Snippet of relevent code: (we use custom functions on our site ie: entry)
For instance say $id=615
<?php
while (list ($id, $name, $class, $desc, $range, $damage, $cost,$hide) = entry ($items) )
{
if ($hide =='0')
{
$JavaScriptArrayParms .= '"' . $id . '",';
$list .= $id . ',';
?>
<tr id="tr<?php echo $id; ?>"> //Thus tr615 for this example
<td>
<input type="checkbox" name="chk<?php echo $id; ?>" onclick="updateStoreTable(this.form, this, <?php echo $id; ?>)" />
<input type="hidden" name="cost<?php echo $id; ?>" value="<?php echo $cost; ?>" />
</td>
<td><?php echo $name; ?></td>
<?php if (! in_array($catid, $noclass)){ echo "<td>$class</td>";}?>
<td><?php echo $desc; ?></td>
<?php if (! in_array($catid, $norange)){ echo "<td>$range</td>";}?>
<td><?php echo $damage; ?></td>
<td><?php echo $cost; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="hidden" name="list" value="<?php echo $list; ?>" />
<input type="button" value="Purchase!" onclick='validatePurchase(this)' />
<input type="reset">
</form>
Relevant JS: (which used to be document.all.store... or just document.all.. in some cases. I hope I fixed it the right way)
<script language="javascript">
var startmoney = <?php echo $currMoney; ?>;
function canAfford(t,id)
{
if(t.checked) return;// don't touch if checked for buying.
//alert("canAfford("+t+","+id+");");
//t.disabled = false;
eval("document.store.getElementByID(foo).disabled = false;");
eval("document.store.getElementByID(foo).checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
}
function cantAfford(t,id)
{
//alert("cantAfford("+t.disabled+","+id+")-- "+t+";");
//alert("before disable");
//t.disabled = true;
eval("document.store.getElementByID(chk"+id+").disabled = "+true+";");
//alert("After disable");
eval("document.store.getElementByID(chk"+id+").checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#555555';");
}
function getCost(id)
{
return eval("document.store.getElementByID(cost"+id+").value");
}
function buying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = 'green';");
document.store.credits.value -= getCost(id);
}
function notbuying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
var creds = new Number(document.store.credits.value);
var cost = new Number(getCost(id));
document.store.credits.value = (creds + cost);
}
function updateStoreTable(f,t,id)
{
var ids = new Array(<?php echo $JavaScriptArrayParms; ?>);
if(t.checked)
buying(t,id);
else
notbuying(t,id);
for(i = 0; i<ids.length; i++)
{
cost = new Number(getCost(ids[i]));
creds = new Number(f.credits.value);
//alert("COST: " +(cost)+"\nCREDITS: "+creds+"\nID: "+ids[i]);
// alert("'"+ (cost) + "' > '" + (creds) +"'\n"+(eval(cost > creds)));
// alert("f.chk"+ids[i]+".checked");
if(eval("f.chk"+ids[i]+".checked")) { continue; } //ignore already carted items
if(eval(cost > creds))
cantAfford(eval("f.chk"+id),ids[i]);
else
canAfford(eval("f.chk"+id),ids[i]);
}
}
1st issue:
it has to be getElementById()
(a lower-case d at the end)
2nd:
When using eval, the code will be evaluated as:
document.getElementById(tr615).style.background = '#000000';
..what will force the error, because the tr615 is not enclosed by quotes, so javascript expects a variable tr615.
the line must look like this:
eval("document.getElementById('tr"+id+"').style.background = '#000000';");
But: Why do you use eval here, this can be done without eval:
document.getElementById('tr'+id).style.background = '#000000';

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