is there a way to exchange variables between JavaScript and PHP - php

I have build a website in Drupal, and I am trying to create a fun way to get members involved with the site by building a userpoint system, the system is all in place, but I'm trying to make a shop where they can buy 'titles'.
This is the script I wrote for the shop, with a bit of error handling, but I'm stuck with a problem,
In my JavaScript, I have the function buyitem( ) with 2 variables, which I want to use in my PHP functions which check everything in my database, is there a way to get those variables from JavaScript to the PHP function I wrote without going to an external PHP file?
<?php
include "php-scripts/DBConnection.php";
$con = getconnection();
mysql_select_db("brokendi_BD", $con);
function getKarma()
{
$result = mysql_query("SELECT * FROM userpoints WHERE uid='getUID()'");
$row = mysql_fetch_array($result);
$currentkarma = (int)$row['points'];
return $currentkarma;
}
function getUID()
{
global $user;
if ($user->uid)
{
$userID=$user->uid;
return $userID;
}
else
{
header('Location: http://brokendiamond.org/?q=node/40');
}
}
function hasRole($roleID)
{
$usersid = getUID();
$returnValue = false;
$result = mysql_query("SELECT * FROM users_roles");
while ($row = mysql_fetch_array($result))
{
if ($row['uid'] == $usersid)
{
if ($row['rid'] == $roleID)
{
$returnValue = true;
break;
}
}
}
return $returnValue;
}
function enoughKarma()
{
if ( getKarma() >= $requiredKarma)
{
return true;
}
else
{
return false;
}
}
function buyRole()
{
$currentKarma = getKarma();
$newkarma = $currentKarma - $requiredKarma;
$userID = getUID();
mysql_query("UPDATE userpoints SET points = '$newkarma' WHERE uid='$userID'");
mysql_query("INSERT INTO users_roles (uid, rid) VALUES ($userID, $roleID)");
}
?>
<script type="text/javascript">
buyItem(1 , 0);
function SetStore()
{
}
Function buyItem(itemID,reqKarma)
{
if (<?php enoughKarma(); ?>)
{
<?php buyRole(); ?>
}
else
{
alert('You do not have enough Karma to buy this title.');
}
}
</script>

PHP is a server side script and javascript is a client side, server side scripts are executed before the page loads, meaning your javascript cannot pass variables to it, BUT you can how ever pass php variables to your js.
Best solution in your case is to use ajax to send those variables to php and have the php set variables on it's side, this doesn't quite solve your problem, but with some creativity in your code you can make it happen.

you can either reload the page (which I doubt is what you'r looking for) or make an ajax call to your php script sending the 2 variables.
if you're using jQuery, this should give you an idea of how to do this

Related

How to use a PHP function for multiple calls within the same PHP page?

I am trying to use a php function to get the prices of a tola (11.664 grams) at an order status page. The function uses a php page 'priceApi4CurCtrl.php' that fetches the price data from a website using an external API. My function is as follows:
function tolaPrice($cur_pick) {
require('priceApi4CurCtrl.php');
if($cur_pick == 'pkr') {
$tola_price = $bitprice_pkr*10*11.664;
return $tola_price;
} elseif($cur_pick == 'usd') {
$tola_price = $bitprice_usd*10*11.64;
return $tola_price;
} elseif($cur_pick == 'aed') {
$tola_price = $bitprice_aed*10*11.64;
return $tola_price;
}
}
// Succeeds for the first call as under
$cur_pick = 'pkr';
echo tolaPrice($cur_pick);
// Fails for the second call as under
$cur_pick = 'aed';
echo tolaPrice($cur_pick);
The function works fine for the first call using echo tolaPrice($cur_pick). However, it fails all subsequent calls and hence I am unable to complete the order status of second and subsequent orders.
I am not sure how to work around this.
Instead of trying to wrap an if else loop in a function, I simply calculated the prices in a separate file named tola_price.php as follows:
include('priceApi4CurCtrl.php');
$tola_price_pkr = $bitprice_pkr*10*11.664;
$tola_price_usd = $bitprice_usd*10*11.64;
$tola_price_aed = $bitprice_aed*10*11.64;
And then called the tola_price.php within my script with if else loop as follows:
require_one('tola_price.php');
if($cur_pick == 'pkr') {
$tola_price = $tola_price_pkr;
} elseif($cur_pick == 'usd') {
$tola_price = $tola_price_usd;
} elseif($cur_pick == 'aed') {
$tola_price = $tola_price_aed;
}
And then used the prices to build further script.
Thanks to those who offered help

I'm trying to save data in memcached from a php script so that my website can directly use the data

The script works fine and is setting the data, but the website code is unable to use it and is instead setting its own memcached values. My website code is written in codeIgniter framework. I don't know why this is happening.
My script code :-
function getFromMemcached($string) {
$memcached_library = new Memcached();
$memcached_library->addServer('localhost', 11211);
$result = $memcached_library->get(md5($string));
return $result;
}
function setInMemcached($string,$result,$TTL = 1800) {
$memcached_library = new Memcached();
$memcached_library->addServer('localhost', 11211);
$memcached_library->set(md5($string),$result, $TTL);
}
/*---------- Function stores complete product page as one function call cache -----------------*/
function getCachedCompleteProduct($productId,$brand)
{
$result = array();
$result = getFromMemcached($productId." product page");
if(true==empty($result))
{
//------- REST CODE storing data in $result------
setInMemcached($productId." product page",$result,1800);
}
return $result;
}
Website Code :-
private function getFromMemcached($string) {
$result = $this->memcached_library->get(md5($string));
return $result;
}
private function setInMemcached($string,$result,$TTL = 1800) {
$this->memcached_library->add(md5($string),$result, $TTL);
}
/*---------- Function stores complete product page as one function call cache -----------------*/
public function getCachedCompleteProduct($productId,$brand)
{
$result = array();
$result = $this->getFromMemcached($productId." product page");
if(true==empty($result))
{
// ----------- Rest Code storing data in $result
$this->setInMemcached($productId." product page",$result,1800);
}
return $result;
}
This is saving data in memcached. I checked by printing inside the if condition and checking the final result
Based on the CodeIgniter docs, you can make use of:
class YourController extends CI_Controller() {
function __construct() {
$this->load->driver('cache');
}
private function getFromMemcached($key) {
$result = $this->cache->memcached->get(md5($key));
return $result;
}
private function setInMemcached($key, $value, $TTL = 1800) {
$this->cache->memcached->save(md5($key), $value, $TTL);
}
public function getCachedCompleteProduct($productId,$brand) {
$result = array();
$result = $this->getFromMemcached($productId." product page");
if( empty($result) ) {
// ----------- Rest Code storing data in $result
$this->setInMemcached($productId." product page",$result,1800);
}
return $result;
}
}
Personally try to avoid 3rd party libraries if it already exists in the core framework. And I have tested this, it's working superbly, so that should fix this for you :)
Just remember to follow the instructions at http://ellislab.com/codeigniter/user-guide/libraries/caching.html#memcached to set the config as needed for the memcache server

Switching from mysql to mysqli issues

Below is some code that works fine, however it used mysql_* and i dont want that anymore. I have tried to redo this section in mysqli but it's not working. I can post my entire code if you wish, but i am certain i know where the issue lies. Below is the code:
Old:
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT client_id FROM clients WHERE client_email_address = '{$this->_username}' AND client_password = '{$this->_pass_sha1}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
New:
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows)
{
list($this->_id) = #array_values($data->fetch());
return true;
}
else
{
return false;
}
}
I'm still learning mysqli and not quite ready for PDO stuff as i found that a little confusing. As i say, this whole script works perfectly with mysql_* but not so much with mysqli. When i try and log in my form doesnt display any errors nor does it push forward to the next page, so i know its this bit that is the issue
it is advised to use a helper function, either with old mysql or modern mysqli
public function verifyDatabase()
{
$sql = "SELECT client_id FROM clients WHERE email = ? AND password = ?";
return $this->db->getOne($sql ,$this->_username,$this->_pass_sha1);
}
Also note that dbConfig.php should not be included in the every method but, but only once. While DB handler should be assigned to a class variable in the constructor.
Change your code to this. I'm not saying it will fix problems but will be better.
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows > 0)
{
$result = $data->fetch();
$this->_id = $result['client_id'];
return true;
}
else
{
return false;
}
}
You can also put var_dump($result); after the $result = $data->fetch(); line to print out what exactly is being returned.

Code doesn't make sense -- two conditionals within PHP try

I have inherited an application that is not doing what it's supposed to do. I have isolated the problem to the database not being properly attached. The programmer wrote this function that seemingly is suppose to evaluate whether the database is attached, calling the "attachPaymentDatabase()" function to attach it if it's not.
function attachPaymentDatabaseIfNotDoneAlready()
{
global $db;
global $hasPaymentDatabaseAttached;
// Determine if we have attached the payment tables, and if not, add them.
$hasPaymentDatabaseAttached = false;
try {
// this new way should work the best-- looking for PAY.
$alldb = queryall($db, "PRAGMA database_list;");
for ($i = 0; $i < count($alldb); $i++)
{
$alldb[$i] = array_change_key_case($alldb[$i], CASE_LOWER);
if (strtolower($alldb[$i]['name']) == 'pay')
{
debugEmail("condition 1 worked.");
$hasPaymentDatabaseAttached = true;
break;
}
}
// if its name changed this will also work
if (!$hasPaymentDatabaseAttached)
{
$r = #$db->querySingle("SELECT * FROM PAY_PARAMETER;");
$hasPaymentDatabaseAttached = true;
debugEmail("condition 2 worked.");
}
}
catch(Exception $e)
{
}
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
}
I have written a debugEmail() function that emails me a defined message with a timestamp as used above. When executing the code from the application, I can see that "condition 2 worked." is being called one second before "nothing worked.".
I don't understand how this can be. If debugEmail("condition 2 worked."); is executing, then so should too $hasPaymentDatabaseAttached = true; in which case this should not execute:
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
But it clearly is.
What is going on here?!?!?!?
No it shouldn't, because $hasPaymentDatabaseAttached is set to true in the first condition. In still nonsense at all, but it works as described.

Update Class variable outside PHP Class

I'm gonna make this too complicated, just going to break it down to the main parts.
I have a form that changes the boolean of a variable when the form gets submitted, however it gets called by a function, the function has to change the variable.
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
}
}
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true. When I do var_dump($up->yesno), it says false when it should be true. If I do this:
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
var_dump($this->yesno); // <-- outputs true
}
}
So how come I cannot get the variable to print out true in a seperate script?
EDIT:
$sql = "SELECT boolean
FROM config
WHERE boolean = 'true'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$up->updateBool();
}
else
{
header("Location: index.php?d=none");
}
This is part of the code where it gets called. I can confirm there are more than 1 record in the SQL statement.
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true
You seem to be switching to a new page, where $up will be a new object. Objects do not persist across requests. PHP "loses its memory" when you call a new page, and all variables are started from scratch.
To persist values across page requests, you would need to use something like sessions.
class updates
{
public $yesno;
function __construct(){
$this->yesno = false;
}
function updateBool()
{
$this->yesno = true;
}
}

Categories