John Davidson

How to correctly call PHP function with arguments from Javascript?

0 comments
Message:


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.



My Answer:
;_ userScore--;_ userScore_span.innerHTML = userScore;_ if (userScore === 0) {_ rezultat_p.innerHTML = "Game Over!";_ // Call PHP function to update high score in MySQL_ updateHighScore(userScore);_ }_}_function updateHighScore(score) {_ // Call PHP function to update high score in MySQL_ // This is where I am stuck_}_index.php_The issue here is that you cannot directly call a PHP function from JavaScript. You need to make an AJAX request to a PHP file that contains the function you want to call. Here is how you can do it:_apps.js_function updateHighScore(score) {_ var xhr = new XMLHttpRequest();_ xhr.open('POST', 'updateHighScore.php', true);_ xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');_ xhr.onreadystatechange = function() {_ if (xhr.readyState == 4 && xhr.status == 200) {_ console.log(xhr.responseText);_ }_ };_ xhr.send('score=' + score);_}_updateHighScore.php_Make sure to replace 'updateHighScore.php' with the correct path to your PHP file. This should allow you to call the PHP function with arguments from JavaScript.

Rate this post

5 of 5 based on 4088 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us