The Problem:
Hello, i am trying to call a php file from node.js with AJAX, but when i do, the session variables return undefined and the database doesn't update. However, the php file does work because i tested it with a link in the browser. Unfortunately, i can not just define the session variables as data for AJAX because i can not include php in javascript or html. (Node JS doesn't allow me to change my index.html to index.php).
What Works:
- The File: When i place the php file as a link in the browser, the database is correctly updated and everything works perfectly.
- AJAX: When i call the php file from AJAX, it does echo the success message but when i changed the success message to one of the session variables, it returns blank. (This is how i found out that the variables are the problem)
The Code:
PHP:
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();
}
?>
mysql.php
<?php
class Mysql
{
protected $dsn;
protected $username;
protected $password;
public $db;
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;
}
}
?>
JS:
app.js
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {},
success: function (data) {
alert(data);
}
});
Conclusion:
I was thinking that when i deploy the node server from index.php (my website's index file - not node's which is index.html) then i could send the php variables to like a json file with a global database and access that from node, but i tried to research it and have no idea how that works.
I am a beginner to PHP so i am open to many different solutions!
P.S. The most secure solution is preferred because my website uses real money.
Thanks for helping out!