AJAX不从JS调用php文件吗?

时间:2018-06-27 00:24:17

标签: javascript php jquery ajax html5

问题:

您好,我确定我的PHP文件可以正常工作,但不幸的是我的ajax代码无法正常工作。我将ajax放置在javascript函数中,以便在需要时调用文件,但是在执行该函数时,什么也没发生。


代码:

这是我的JS代码:

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
        $.ajax({
        type: "POST",
        url: 'http://cashballz.net/game/5game/subtract5.php',
        data: { },
        success: function (data) {
            alert(data);
        }
    });
}

我的HTML:

<script src="//code.jquery.com/jquery-2.2.0.min.js"></script>

甚至是我的PHP:

<?php
session_start();

$servername = "localhost";
$username = "myName";
$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;

$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();


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

$conn->close();
?>

结论:

我不明白为什么我的文件没有被调用。

我有JQuery,我对AJAX进行了很多研究,并查看了该网站上的其他类似问题。

我转到了文件链接,它可以正常工作,所以我很确定这是一个JavaScript错误。

我擅长JS,但是是PHP和JQuery的初学者。

感谢您的所有帮助。

2 个答案:

答案 0 :(得分:0)

尝试修改ajax调用以包含错误处理程序。例如:

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

答案 1 :(得分:0)

PHP: header('Access-Control-Allow-Origin: *');允许跨域访问。