The Problem:
I am currently making a game that requires access to database values to execute a PHP file with ajax. The PHP file works when I put the link in the browser, but not when called by ajax. This is because the session variables are not being passed.
I can not change the index.html to index.php in my Node game because that causes many issues, so I need a way to pass the variables from my database to my javascript without using direct PHP code in my javascript.
The Code:
Here is my PHP Code:
mysql.php
function __construct()
{
$this->dns= 'mysql:dbname=cashball_accounts;host=localhost;charset=utf8';
$this->username= 'myUser';
$this->password= 'myPass';
$this->db = new PDO($this->dns, $this->username, $this->password);
}
public function setCashAmount($cash_amount, $id)
{
$sql = "UPDATE users SET cash_amount = :cash_amount - 0.05 WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':cash_amount', $cash_amount, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$result = $stmt->execute();
return $result;
}
}
?>
subtract5.php
<?php
header('Access-Control-Allow-Origin: http://cashballz.net:3000', false);
include 'mysql.php';
session_start();
$cash_amount = $_SESSION['cash_amount'];
$userid = $_SESSION['id'];
$_SESSION['cash_amount'] -= 0.05;
$mysql = new Mysql();
$result = $mysql->setCashAmount($cash_amount,$userid);
if($result)
{
echo "5 cents have been subtracted!";
}
else
{
session_start();
session_unset();
session_destroy();
}
?>
My JS Code:
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {},
success: function (data) {
alert(data);
}
});
The Conclusion:
So when I put the link in the browser, the PHP code is fine and executes perfectly, but when I call it from AJAX the file is executed, but the session variables are undefined.
What do I do?
(I could pass the variables into the JS file and put them as data under AJAX, but I don't know how to pass the session variables without being able to have an index.php.
All of my node files are in a different folder that doesn't include PHP, and the PHP files are in one folder back with all the other PHP files.
Thanks for the help.