douzi9211 2018-07-03 22:22
浏览 63

AJAX PHP在Node.js中不起作用

The Problem:

When I put a PHP file link in the browser, it works perfectly fine and updates my database as expected.

When I call it with ajax from node.js, it echoes the success message but the DB does not update.

The Session variables are undefined, so when I changed them to real numbers the code still did not work. What is going wrong?


My PHP Code:

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 $cash_amount; 
} 
else 
{ 
session_start(); 
session_unset(); 
session_destroy(); 
}
?>

mysql.php:

<?php
class Mysql 
{ 
protected $dsn; 
protected $username; 
protected $password; 
public $db; 


function __construct() 
{ 
//change this to your info (myDBname, myName, myPass) 
$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; 
} 

} 
?>

My node.js (app.js) AJAX:

//cut 5 cents from account - php function
        $.ajax({
        type: "POST",
        url: 'http://cashballz.net/game/5game/subtract5.php',
        data: {}, 
        success: function (data) {
            alert(data);
        }
    });

Recap:

  • PHP File works from site.com with the same AJAX code, and by putting its link in the browser.
  • PHP File is executed from node, but does not update the DB
  • PHP File has undefined $_SESSION variables but when replaced, the DB still does not update

Possible solutions:

  • Is there extra code i can put in AJAX to tell it to "pipe" the call to site.com to call the file instead of calling it straight from node?

Extra Info:

  • No errors in error logs or console
  • I need to use AJAX to input data into the file later on
  • Solution must be secure

Thanks for the help!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Matlab问题解答有两个问题
    • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
    • ¥15 LCD12864中文显示
    • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
    • ¥15 gsoap生成onvif框架
    • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
    • ¥15 stm32的can接口不能收发数据
    • ¥15 目标检测算法移植到arm开发板
    • ¥15 利用JD51设计温度报警系统
    • ¥15 快手联盟怎么快速的跑出建立模型