This question is pretty much what I am trying to do, but I cannot understand how to use it in my context.
I have tried the marked answer and the answer submitted by xdazz. Both of these answers seem to send the variables from the client-side to the php script through POST. When I attempt this, it simply does not hit my alerts, which leads me to believe that the php script receiving the POST variables is never being executed.
Here is the function which runs when I click a button on my js canvas
function updateLeaderboard()
{
alert("before");
$.post("process.php", { postantNum: antNum, postantRate: antRate },
function(data)
{
alert(data);
} );
alert("after");
}
Here is the process.php file
<?php
$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];
echo $antNum;
echo $antRate;
$con=mysqli_connect("localhost","root","pass","login");
mysqli_query($con,"UPDATE userdata SET `words`='$antNum' WHERE `player`='$antRate'");
?>
HTML running the javascript:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>p5.js example</title>
<style> body {padding: 0; margin: 0;} </style>
<script src="../p5.min.js"></script>
<script src="../addons/p5.dom.js"></script>
<script src="../addons/p5.dom.min.js"></script>
<script src="../addons/p5.sound.min.js"></script>
<script src="antclicker.js"></script>
</head>
<body>
</body>
</html>
I wish to be able to send in antNum and antRate from the client-side js game I have created to the database for storage.
There are no error messages, I just know it never gets to the echos in the process.php and never hits the after alert, only the before alert is triggered.
EDIT:
Now since I have dipped my feet into chromes tools, I have discovered that on the line $.post("process.php", { postantNum: antNum, postantRate: antRate },
(yes I have changed the code a little bit) I get the error : ReferenceError: $ is not defined, how can it be singling out the "$". I'm guessing this probably means that there are some syntax errors nearby.
mysqliyou should be using parameterized queries andbind_paramto add any data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put$_POST,$_GETor data of any kind directly into a query, it can be very harmful if someone seeks to exploit your mistake.mysqliis significantly less verbose, making code easier to read and audit, and is not easily confused with the obsoletemysql_queryinterface where missing a singleican cause trouble. Example:$db = new mysqli(…)and$db->prepare("…")The procedural interface is largely an artifact from the PHP 4 era whenmysqliAPI was introduced and should not be used in new code.mysqliso any mistakes made aren’t easily ignored. Many return values cannot be ignored, you must pay attention to each one. Exceptions don’t require individual checking, they can be caught at a higher level in the code.