I made a JS snake game using HTML5 canvas. If the user loses the game, the score is sent to the database using AJAX. The PHP script compares it to the current value and saves it if it is larger. Now, I am struggling to find a way to update the score inside the game because the page never gets reloaded(and i don't want it to). Here is my PHP script:
$query = "SELECT * FROM shighscore";
$result = mysqli_query($link, $query);
$score = mysqli_fetch_array($result)[0];//this is the highscore
if(array_key_exists("jsscore", $_POST)){//if AJAX posted the var
if($_POST["jsscore"] > $score){
$query = "UPDATE shighscore SET score = ".mysqli_real_escape_string($link, $_POST['jsscore']);
mysqli_query($link, $query);
$score = $_POST["jsscore"]; //score var is updated
echo "<p id = 'dbvalue'>".$score."</p>";//this is echoed with the new score value
}
}
In my JS, I do this:
$.ajax({
method: "POST",
data: {jsscore : score}//variable with the current score
}).done(function(data){
var dbscore = document.getElementById("dbvalue").innerHTML;//gets value of the <p> that was echoed by php
alert(dbscore);//it never alerts
$("#dbvalue").remove();//remove the unneeded <p> tag
if(dbscore == score){
$("#worldscore").html("World High <br>Score: " + score);//updates html
}
});
I used other methods like making a function where:
var db = Number("<?php echo $score;?>");
I think that the line of code is only updated when the page first opens. Since I do not reload the page, the new value of score never goes to the JS variable. What can I do? The error in the console is "cannot read property of innerHTML if null". Why is the paragraph with the id of 'dbvalue' null if it is echoes right before the js accesses it?
Can I do all this in the same file("index.php") or do I have to make another one as shown here?