jQuery getJSON - Possible Syntax Error - php

Well I've managed to put the following together from various examples, however I don't believe the javascript function is even being called, below is all my code:
Javascript:
<script type="text/javascript" src="coding/jquery.js"></script>
<script type="text/javascript">
function showHint(quantity, price){
document.getElementById("txtcost").innerHTML="being called values" + quantity + price;
$.getJSON('http://website.com/ecommerce/coding/validation/calprice.php', {q: quantity, p: price}, function(data){
$('#txtcost').html('Total: ' + data.total);
$('#txtvat').html('VAT: ' + data.vat);
});
}
</script>
Display
<span id="txtcost" style="color:#060"></span>
<span id="txtvat" style="color:#060"></span>
PHP
<?php
echo "being called";
function data() {
$q = $_GET["q"];
$p =&$_GET["p"];
$total = $p * $q;
if($q >= 10)
{
$total = ($total / 10) * 9;
//echo '<strong>£ ' . $total . '</strong><span style="font-size:10px; font-weight:bold;"> Discount applied.</span>';
echo json_encode(array('total' => $total, 'vat' => '10.00'));
}
else{ echo '<strong>£ ' . $total . '<strong>'; }}
?>
Hope that helps
Note: the code isn't perfect, I want to get the initial functionality working.
EDIT:
SO far I've managed to establish:
The function is being called
The correct values are being passed into the function

For one thing, you need to use JavaScript's dot notation to reference object properties, and not PHP's arrow operator:
data.total
instead of
data->total

i think a problem with your quotes on line 1 you seem to be breaking into php, maybe you need to use something more like:
<input name="quantity" type="text" id="quantity" onkeyup="showHint(this.value, ' . $events[0]['price'] . ' )" size="6" />
but hard to say without full code

Related

How to echo/print within a fuction with undefined variables in php?

I am not the best at php but currently I am trying to learn. I can print fine outside of the function but the specific instructions I have been given require me to print the results within the function. I have tried
echo "$area";
echo "calculatearea ()";
ive searched but still cant figure out how to get a print within the function only outside of it.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
return $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
echo "Your rectangle circumference is: " . calculateCircumference() . '<br />' . "Your rectangle area is: " . calculateArea();
}
?>
<!---------------- Form---------------->
<div class="form">
<h3></h3>
<form action="PHP-sida4.php" method="POST">
<p>Length: <input type="text" name="Length"value=""></p>
<p>Width: <input type="text" name="Width"value=""></p>
<input type="submit" name="CalcBT" value="Calculate">
</form>
I need the return value of $area along with what I echo'd in the bottom to actually print within the first function ( calculateCircumference )
You can echo anything you want within the function but it won't show up until you call the function.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
// return $circ;
echo "Your rectangle circumference is: " . $circ . '<br />' . "Your rectangle area is: " . calculateArea();
return;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
calculateCircumference();
}
?>
I hope this helps!
Okay if am getting your question right, to need to return the area and some other text along with the area.
Let's begin with some house cleaning, therefore the $area global variable could be renamed to something else like $results Which will be an array or object. Taking it simple.
Lets go with an associative array where e.g:
$results = [
'area' => null,
'text' = null
];
From that your will be updating $results['area'] from the calculate function and also update the $results['text'] before calling echo, so probably extract the echoed text to another variable.
And now you can access $results anywhere within the file with both the area and the text:
To just be more expressive under CalculateArea() function do something like:
$results['area'] = $area;
Same thing with the echoed text.
You can use echo instead of return in your functions. To call them, your can just use function(); without any additional keyword :
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
echo $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
echo $area;
}
echo "Your rectangle circumference is: " ;
calculateCircumference() ;
echo '<br />' ;
echo "Your rectangle area is: " ;
calculateArea();
You can echo anything anywhere, be it inside a function or outside of it. If an echo is not performing, then there was either an error, or the line where the echo can be found was not executed.
In our case you have removed the echo after your functions, which, coincidentally happened to be the only place where they were called.

About the evil of eval: How to clean up

I'm building a site that will (eventually) be the front-end for a game. I want to be able to dynamically build a list of "powers" that the user is able to purchase. In order to build these lists, I'm using a PHP-based SQL query, then passing it to Javascript for dynamic choices (some powers have prerequisite powers).
I know there's a simpler way to do what I'm doing, but I'm not super concerned with that right now (I will be later, but I'm trying to get this functional and then clean) (again, I know this is non-optimal).
I'm using eval to parse which divs to show, and I want to know how not to.
I'm having issues getting my div names built right in the first place.
Here's my code:
Javascript (separate file)
function upgradeList(passed)
{
var PowerArray = [];
var DetailPowerID = [];
var EscapedPowerID = [];
PowerArray.push([]);
PowerArray = eval(passed);
var OutputThing="";
for (i=0;i<PowerArray.length;i++)
{
DetailPowerID[i] = 'detail' + PowerArray[i][0];
EscapedPowerID[i] = "'" + DetailPowerID[i] + "'";
}
for (i=0;i<PowerArray.length;i++)
{
OutputThing = OutputThing + "<br><a href='#' onClick='showUpgradeDetails(" + DetailPowerID[i] + ")'>" + PowerArray[i][2] + "</a><div class='hidden' id='" +
DetailPowerID[i] + "'>" + PowerArray[i][3] + "</div>"; }
document.getElementById("secondUpgrade").innerHTML=OutputThing;
document.getElementById("secondUpgrade").style.display='block';
}
}
PHP writing HTML and JS:
{$AbleToUpgrade and $UpgradeList are both 2d arrays built from SQL queries)
echo "<script name='UpgradeList'>";
settype($UpgradesListSize[$i],"int");
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "var UpgradeList" . $AbleToUpgrade[$i][0] . " = new Array();";
for ($j=0;$j<=$UpgradesListSize[$i];$j++)
{
echo "UpgradeList" . $AbleToUpgrade[$i][0] . ".push(Array('"
. $UpgradeList[$i][$j][0] . "', '"
. $UpgradeList[$i][$j][1] . "', '"
. $UpgradeList[$i][$j][2] . "', '"
. $UpgradeList[$i][$j][3] . "', '"
. $UpgradeList[$i][$j][4] . "'));";
}
}
echo "</script>";
... and, later...
echo "<div id='SpendUpgrade'>
Select power to upgrade:
<ul>";
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "<li><a href='#' name='UpgradeList" . $AbleToUpgrade[$i][0] . "' onClick='upgradeList(this.name)'>" . $AbleToUpgrade[$i][1] . " - " . $AbleToUpgrade[$i][2] . "</a></li>";
}
echo "</select>
<div id='secondUpgrade' class='hidden'>
</div>
<div id='thirdUpgrade' class='hidden'>
</div>
</div>";
When I load the page, I wind up with generated text like this:
Real Armor
and the corresponding div:
<div class="hidden" id="detail21" style="display: none;">Your armor only works in the Waking</div>
In order to get the div to show (display:block;), I need to call the function like so:
showUpgradeDetails("detail21")
but I can't make JS / PHP write the quotes correctly. Help (with any or all of this?) please!
I found a resolution, and it wasn't JSON.parse().
I changed PowerArray = eval(passed); into PowerArray = window[passed];.
Because passed contains the name of a variable, and is not the variable itself, I couldn't work directly with it. However, because it was a string that held exclusively the name of a globally-defined variable, I could pass it to the window[] construct and have it work.

AJAX PHP MicroBlog Update feed

I'm stuck on my project for college, I've been working on a small time microblog, this may seem silly but I have no idea on how to make the feed auto refresh without killing my monthly bandwidth, here is the code I'm using atm,
Data.php
<?php
// connect to the database
require_once 'script/login.php';
//show results
$query = "SELECT post, PID, fbpic, fbname, fblink, post_date, DATE_FORMAT(post_date, 'Posted on %D %M %Y at %H:%i') AS pd FROM `posts` WHERE 1\n"
. "ORDER BY `post_date` DESC LIMIT 0, 30 ";
$result = #mysql_query ($query);
if ($result) { //If it ran ok display the records
echo '<div id="feed">';
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo '<a name="' . $row['PID'] . '"></a><div id="postsint"><a target="_blank" href="http://www.facebook.com/' . $row['fblink'] . '"><img id="dp" title="' . $row['fbname'] . '" src="https://graph.facebook.com/' . $row['fbpic'] . '/picture"/></a><div id="posttext">' . base64_decode($row['post']) . '<blockquote>' . $row['pd'] . '</blockquote>Share</div></div><br />';
};
echo '</div>';
mysql_free_result ($result);
} else { //if it did not run ok
echo '<h2 id="error">Wisprs could not be retrieved. We apologise for any inconvienience.</h2>'; //public message
echo '<p id="error">' . mysql_error() . '<br /><br /> Query: ' . $query . '</p>'; //debugging message
}
mysql_close(); // Close database connection
?>
content.php
<div id="postlist"> FEED GOES HERE.</div>
All im trying to do is check for updates every 2 seconds and if there is updates then show them in #postlist
It's been a 3 week struggle and I don't know any JavaScript, it's annoying me and I just want to finish this project so I can go to University and maybe learn to do this myself =/
Cheers in advance.
PS - I'm only guessing that it's Ajax but my tutor recommended this site for an answer if I get stuck
Hopefully you are allowed to use jQuery.
Add to content.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function getFeed(){
$.post('Data.php',function(data){
$("#postlist").html(data);
});
setTimeout("getFeed();",2000);
}
window.onload = getFeed();
</script>
getFeed() is called on page load, then calls itself every 2000 milliseconds and appends the data received from Data.php into your postlist element.
This is brute forcing it, making it constantly delete the old html in the postlist div and create all new html every 2 seconds. If you have images that you are loading you will need a more complex solution.
If you use KnockoutJS and jQuery, this might be a good starting point:
http://jquery.com/
http://knockoutjs.com/
content.php
<script type="text/javascript">
$(function() {
// Define our view model that we will feed to KnockoutJS.
var viewModel = {
posts: []
};
// We'll use this variable to keep track of the last post we
// received. When we send our GET request, our php script will be
// able to see $_GET['last_post_date'] and only return the posts
// that come after that.
var last_post_date = null;
// This is the function that will get called every 2 seconds to
// load new data.
var getData = function() {
$.ajax({
url: "/data.php",
data: {
last_post_date: last_post_date
}
}).done( function( data ) {
// We'll assume data.php will give us a JSON object that looks
// like: { posts: [] }
// Append the new posts to the end of our 'posts' array in our
// view model.
viewModel.posts.concat( data.posts );
// Tell KnockoutJS to update the html.
ko.applyBindings( viewModel );
// Store the date of the last post to use in our next ajax call.
last_post_date = viewModel.posts[ viewModel.posts.length - 1 ].post_date;
});
// In 2 seconds, call this function again.
setTimeout( getData, 2000 );
};
// grab the first set of posts and start looping
getData();
});
</script>
<!-- We're telling KnockoutJS that for each 'row' in our 'posts' array, apply
the template named 'row-template'. -->
<div id="postlist"
data-bind="template: { name: 'row-template', foreach: posts }"></div>
<!-- This is the KnockoutJS template that we referenced earlier. Of course,
you don't have to use KnockoutJS to do this. There are plenty of other ways
to do this. Do keep in mind that you'll minimize your bandwidth usage if you
send JSON and use an HTML template rather than loading the same HTML over
and over again. -->
<script type="text/html" id="row-template">
<a data-bind="attr: {name: PID}"></a>
<div id="postsint">
<a target="_blank" data-bind="
attr: {
href: 'http://www.facebook.com/' + fblink
}
">
<img id="dp" data-bind="
attr: {
title: fbname,
src: 'https://graph.facebook.com/' + fbpic + '/picture'
}
" />
</a>
<div id="posttext">
<!--ko text: post--><!--/ko-->
<blockquote data-bind="text: pd"></blockquote>
<a data-bind="
attr: {
href: 'https://www.facebook.com/dialog/feed?' +
'app_id=505747259483458&' +
'link=http://www.wisp-r.com/share.php?' +
'id=' + PID + '&' +
'picture=http://www.wisp-r.com/images/app-icon.png&' +
'name=Wispr by ' + fbname + '&' +
'caption=' + pd + '&' +
'description=' + post + '&' +
'redirect_uri=http://www.wisp-r.com/share.php?id=' + PID
}
">
Share
</a>
</div>
</div>
<br />
</script>
data.php
<?php
// ... do sql stuff ...
// Remember to add a WHERE statement to filter out posts that are earlier than
// or equal to $_GET['last_post_date'].
$posts = array();
if ( $result ) {
while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
array_push( $posts, $row );
}
}
echo json_encode( array( 'posts' => $posts ) );

javascript to php value not sending/adding

I must be tired or something because i am unable to get this line of code to work:
var all = color.val('all');
$('#cssColor" + <?php echo $page ?> + "', parent.document).attr("background-color", all.hex);
I even have a textbox with the page value as well and i try:
var all = color.val('all');
$('#cssColor" + $('#txtPageValue').val() + "', parent.document).attr("background-color", all.hex);
I can not seem to send the page value!
Try to change this one:
$('#cssColor" + <?php echo $page ?> + "',
to:
$('#cssColor<?php echo $page ?>',
And also, for the second one:
$('#cssColor" + $('#txtPageValue').val() + "',
to:
$('#cssColor' + $('#txtPageValue').val(),
I am not sure how you are assigning the all variable, but assuming it is getting assigned correctly, you could rewrite your code something like this to get the value to appear in the right place in your javascript:
<?php echo "<script type='text/javascript'>
//code somewhere in here should define the color object
var all = color.val('all')
$('#cssColor" . $page . "', parent.document).attr('background-color', all.hex);
</script>"; ?>
This writes the javascript to the document, without breaking the echo function in the middle.
Or, you could do this:
var all = color.val('all');
$('#cssColor'+<?php echo $page; ?>, parent.document).attr('background-color', all.hex);

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

Categories