【问题标题】:Call a PHP file from Javascript (AJAX?)从 Javascript (AJAX?) 调用 PHP 文件
【发布时间】:2018-06-26 02:39:42
【问题描述】:

问题:

您好,我在网上研究过AJAX,但不是很了解。我正在尝试从 javascript 函数中调用 php 文件,但不幸的是它无法正常工作。我正在尝试一切,但我仍然没有得到它。希望这里的人能以我的代码为例给我解释一下。


Javascript:

这是我要调用文件的函数:

function countdownEnded() {
    //make serverscreen dissapear
        document.getElementById('serverScreenWrapper').style.display = 'none';
        document.getElementById('serverScreenWrapper').style.opacity = '0';
        document.getElementById("cashOutNumTwo").style.right = '150%';
        document.getElementById("cashOutNumOne").style.right = '150%';
//start Timer
        setInterval(gameTimer.update, 1000);
//make player move again
        socket.emit('4');
        socket.emit('6');
//make game appear
        document.getElementById('gameAreaWrapper').style.opacity = 1;
//play sound
        document.getElementById('spawn_cell').play();
//cut 5 cents from account - php function
        //CALL PHP FUNCTION HERE WITH AJAX
}

所以php文件基本上是| ../../../../subtract5.php |与其他文件有关。


PHP:

这是文件:

<?php
session_start();

$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDBname";
$cash_amount = $_SESSION['cash_amount'];

// Create connection

$userid = $_SESSION['id'];

// You must enter the user's id here. /\

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] -= 0.05;
$newAmount = $cash_amount - 0.05;

$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
$result = $conn->query($sql);

if($result)
{
   echo "5 cents have been subtracted!";
}
else
{
   echo mysqli_error($conn);
   session_start();
   session_unset();
   session_destroy();
}

$conn->close();
?>

结论:

如何从函数中调用此文件,并且作为奖励:如果我想将 javascript 变量发送到文件以用于更新我的数据库,我该怎么做?

非常感谢您的帮助!

【问题讨论】:

    标签: javascript php ajax database html


    【解决方案1】:

    将这部分代码写成你的javascript函数

    function countdownEnded() {
           /* Your Code */
         $.ajax({
            type: "POST",
            url: '/subtract5.php',
            data: { },
            success: function (data) {
                alert(data);
            }
        });
    }
    

    【讨论】:

    • 所以即使文件是几个文件夹,我也不必写关系? (../../../)
    • 是的。您必须指定文件的确切位置。
    • 如果文件存储在 html-root/your-project/folder1/folder2/ 中,url 就像 ~/folder1/folder2/subtract5.php
    • 好吧,我测试过了,数据库根本没有更新。你知道为什么吗?
    • @Patrick 您是否包含了使 AJAX HTTP 调用正常工作所需的脚本文件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多