I created a memory game using javascript, html, css and PHP without using a framework, i use php to save the player name and the score into MySql database am getting those variables from my javascript and send them using jQuery Ajax post request this is how my code is looks like:
$("#submitScore").on("click", function() {
let playerName = $('#playerName').val();
if(isEmptyOrSpaces(playerName)){
playerName = "Unknown";
}
let data = {"player_name": playerName, "score": totalScore};
$.post("./backend/save_score.php", data, function(){
fetchHighScores();
$("#submitScore").prop('disabled', true);
});
});
everything works fine the only problem that i have is that anyone can send an ajax request using the dev console, so if someone put this line in console and hit enter
$.post("./backend/save_score.php", {"player_name": "Cheater", "score": 1111111111});
it will be saved into my database, am sure that theres a solution for that i searched for CSRF attacks but i didnt got proper answer am new in Ajax world , How can i prevent this kind of actions? i dont want to use a framework am keeping my game as Simple as possible? thanks in advance
You can't.
What you need to do instead is change your approach, and add some server-side validation. Let the JavaScript send your server the user's answers to the questions, rather than the final score. That way the server can check if the answer is correct or not, and the server will calculate the score and return it. This will stop anyone from sending their own made-up score.