简体   繁体   中英

How to correctly call PHP function with arguments from Javascript?

So I am making a Rock Paper Scissors game. I want to make it that when the user loses to the computer, the game finishes or restars and the user's high score is updated in MySQL. I cannot seem to make it work tho. This is what I have so far: The code is big so I will add a small part of it.

apps.js

function lose(user, computer) {
    compScore++;
    userScore_span.innerHTML = userScore;
    compScore_span.innerHTML = compScore;
    rezultat_p.innerHTML = convertWord(user) + " loses to " + convertWord(computer) + ". Game Over!";
    getOutput();
}

function getOutput() {
    jQuery.ajax({
        type: "POST",
        url: 'myAjax.php',
        dataType: 'json',
        data: {functionname: 'gameOver', arguments: [userScore]},

        success: function (obj, textstatus) {
            if( !('error' in obj) ) {
                yourVariable = obj.result;
            }
            else {
                console.log(obj.error);
            }
        }
    });

}

myAjax.php

<?php

function gameOver($highScore){
    session_start();
    require_once 'dbh.inc.php';
    $user = $_SESSION['userid'];
    echo($user);

    $sql = "UPDATE users SET userHighScore = $highScore WHERE userId = $user;";

    $stmt = mysqli_stmt_init($conn);

    if(!mysqli_stmt_prepare($stmt, $sql)){
        header("location: ../leaderboard.php?error=stmtfailed");
        exit();
    }

    mysqli_stmt_bind_param($stmt, "s", $highScore);
    mysqli_stmt_execute($stmt);

    mysqli_stmt_close($stmt);

}
?>

So when I run this, the getOutput function executes but the PHP function doesn't seem to execute. Maybe it is an error in the PHP function, I am not sure.

I think that $user = $_SESSION['userid']; doesn't work properly.

You can't call a PHP function from JavaScript.

You can make an HTTP request to an HTTP endpoint. That HTTP endpoint can be handled by a PHP program . It can either always call the function or conditionally call it (based on the contents of $_POST for example).

eg

$functionname = $_POST['functionname'];
if ($functionname == "gameOver") {
    gameOver($_POST['arguments'][0]);
}

… but you should abstract things so the data you are sending isn't so tightly coupled with the implementation of the PHP.

(Note that your JS is expecting some JSON back in the response but your function doesn't output any. Make sure you deal with that too.)

You can try the below code

 <?php
    if(isset($_POST, $_POST['functionname'], $_POST['arguments'])) {
        switch($_POST['functionname']) {
            case 'gameOver' :
                gameOver($_POST['arguments'][0]);
            break;
            default:
                echo "Unknown method!";
            break;
        }
    }
    else {
        echo "No score posted!";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM