I'm trying to make a snake game within my website, and have been running into the issue of not being able to send score and user data (for a leaderboard) to my SQL database. I'm really new to web dev, so I'm not sure if maybe there's a super simple fix I just keep overlooking. Here's the part of the game's JavaScript code block that I am focusing on:
// snake occupies same space as a body part. reset game
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
//Ask for new user if one isn't registered
if (document.getElementById("userV").innerHTML == "User: ____")
{
document.getElementById("userData").innerHTML = window. prompt("User:");
document.getElementById("userVisible").innerHTML = "User: " +
document.getElementById("userData").innerHTML;
}
/*
*Here is where I need to send user and score data to snake_scores table
*/
snake.x = 160;
snake.y = 160;
snake.cells = [];
snake.maxCells = 4;
snake.dx = grid;
snake.dy = 0;
snake.score = 0;
document.getElementById("scoreData").innerHTML = snake.score;
document.getElementById("scoreVisible").innerHTML = "Score: " + snake.score;
apple.x = getRandomInt(0, 25) * grid;
apple.y = getRandomInt(0, 25) * grid;
}
So overall, my issue is that I can't figure out how to send these JS values through PHP and to my SQL server.
I'll make some assumptions about the game page itself, given that you probably don't want the page to refresh during play a good solution would be Ajax (Asynchronous JavaScript And XML). Essentially this is making a post request in the background to your server without reloading the page.
I find jQuery pretty easy to use: https://api.jquery.com/jQuery.post/
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So using Ajax to post to a url that is expecting the information to then update server side you would access this in php using something similar to the following.
$leaderboard = $_POST['leaderboard']
Hope this points you in the right direction at least. Good luck on the game.