0

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.

7
  • 2
    how, in the php, are you calling the function gameOver? I see it passed as an argument in the data for your ajax call but not how that ajax call is processed Commented Jan 4, 2021 at 12:21
  • 2
    Nowhere in your code do you actually call the 'gameOver' function in PHP. You need to process the POSTed data, and actually call the function found in your functionname parameter. Commented Jan 4, 2021 at 12:22
  • 2
    If that is truly the entire myAjax.php script, you're only defining the function, not calling it. If there is more to that script, then please include that in the question. Commented Jan 4, 2021 at 12:23
  • The variable arguments in your ajax function is an array - presumably that is a single value in the array or multiple? If it is single there should be no need for the array syntax and it'll ake the PHP processing easier Commented Jan 4, 2021 at 12:25
  • 4
    Danger: You are vulnerable to SQL injection attacks that you need to defend yourself from. Commented Jan 4, 2021 at 12:26

2 Answers 2

3

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).

e.g.

$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.)

Sign up to request clarification or add additional context in comments.

5 Comments

it appears though that he is sending an http request to myajax.php but not processing the request correctly
@ProfessorAbronsius — Yes, this answer explains how to handle the request correctly.
indeed it does @Quentin
Indeed, I don't understand that good what I'm doing. So if I add this code to my myAjax.php the function should be called correctly? Because I added it and it doesn't update the high score in the MySQL. That makes me think that maybe the function is not working correctly.
It works now. My mistake was that require_once 'dbh.inc.php'; was in the folder Includes and I had not added it.
0

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!";
    }

2 Comments

Did you know that isset($_POST['functionname'], $_POST['arguments']) can take multiple parameter The Manual
Also you might want to check the spelling of breeak

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.