I am building a game using phaser game development and I want to send the score into mySQL database but JS and PHP don't directly communicate. I am using AJAX but I'm stuck. Here is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Star Runner</title>
<script>window.score=0;</script>
<script src="phaser.js"></script>
</head>
<body>
<script type="text/javascript">
// game goes here
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$(document).ready(function(){
$.ajax({
url: "inscore.php",
type: 'POST',
data: 'score='+score,
cache: false,
success: function(data) {
alert(data);}
});
});
</script>
<h1 style="color:white">Star Runner</h1
</body>
</html>
My php file 'inscore.php' would be:
<?php
include 'login.php';
$score = $_GET['score'];
echo "<p>". $score. "</p>";
//SQL queries
?>
I'm not sure if I should link this page to the php page because I just want the score to update into my database immediately after the game is done. Can someone please help me?
First, there is a little mistake in your code.
Your Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> // code here will not run $(document).ready(function() { $.ajax({ // ... }); }); </script>
It suppose to be:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $.ajax({ // ... }); }); </script>
And here is a example for you:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Star Runner</title> <script src="phaser.js"></script> </head> <body> <h1 style="color:white">Star Runner</h1> <div> Game stage ... </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> // game goes here var Game = { score: 0, run: function() { // your awesome code if (true) { this.gameOver(); } }, gameOver: function() { var _this = this; // send the request $.ajax({ url: "inscore.php", type: 'POST', data: 'score=' + this.score, cache: false, success: function(data) { // balabala console.log(_this); } }); } }; // Run the game Game.run(); </script> </body> </html>
It is better to use OOP (Object Oriented Programming), especially in the game project.
Since you are posting data on your ajax, you should get the data on PHP's $_POST global variable
<?php
include 'login.php';
$score = $_POST['score'];
echo "<p>". $score. "</p>";
//SQL queries
?>
And try to use a php framework like laravel or symfony for this project, even a simplier one like slim would be better for you to get things done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.