-1

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.

nedsmith
  • 65
  • 1
  • 10
  • Can you post the relevant HTML, showing how you get the values and post them? They're not declared in the Javascript anywhere, which also looks a bit wrong. We need more info to help. – Reinstate Monica Cellio May 28 '19 at 21:22
  • 5
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to 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](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or data *of any kind* directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman May 28 '19 at 21:24
  • 2
    Note: The [object-oriented interface to `mysqli`](https://www.php.net/manual/en/mysqli.quickstart.connections.php) is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface where missing a single `i` can cause trouble. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is largely an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman May 28 '19 at 21:24
  • 3
    Note: A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so 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. – tadman May 28 '19 at 21:24
  • none of the two (success/error) alerts show up it's a sign that there's something going wrong before - in javascript. Did you check the console if there are errors shown? As @Archer already stated: `antNum` and `antRate` seem not to be defined. Also look into network tab (of debugging tools [F12]) to see if the request is beeing sent, if you get something back, etc.. – Jeff May 28 '19 at 21:27
  • @tadman Thanks, I am fully aware of my very SQL injection prone project, as my previous questions on this same project also had concerned users. It won't go live until I am sql injection proof. But you are saying that using bind and those other things might help my case? – nedsmith May 28 '19 at 21:34
  • @Jeff the problem is I have no clue how to check the console, I'm just using sublime text, I think there is a way to use chromes console? It seems to daunting to get into at the moment. – nedsmith May 28 '19 at 21:34
  • @Archer I don't believe html is involved in anyway, only as a means to call the js file I have running the game. – nedsmith May 28 '19 at 21:35
  • 4
    It is so ridiculously easy to fix SQL injections by using bound parameters that the number of keystrokes it takes to complain about it is significantly longer than just doing it correctly. As a bonus, if you use placeholder values **you will no longer have annoying, difficult to debug escaping issues**. You'll save time immediately. You'll have fewer bugs. As a bonus you can go live without SQL injections. – tadman May 28 '19 at 21:38
  • @Jeff it's going to take me a good while to understand the network tab under the f12 menu, do you think it is essential to php mysql javascript web dev? – nedsmith May 28 '19 at 21:38
  • Okay. It wasn't clear that it's a JavaScript application and not a web application. In that case, calling a PHP page won't stop the "after" alert from firing, so there's something else wrong. – Reinstate Monica Cellio May 28 '19 at 21:38
  • 6
    The Developer Menu is something you'll need to figure out on an immediate basis, there's no shortcuts here, but the good news is it only takes about 30 minutes to get familiar with where to look and how to read the output. It is impossible to survive as a developer doing JavaScript and AJAX without that fundamental tool. – tadman May 28 '19 at 21:39
  • @tadman okay I will take your word, I have looked at many available fixes like PDO and what you mentioned, but they all seemed, at surface level, to take a long time to implement. Also you see I'm just trying to get functionality at the moment as I have to do a presentation on this project tonight and getting this last section complete would be good. I will make sure to fix all the issues when I publish it. – nedsmith May 28 '19 at 21:42
  • @Archer I apologise for the confusion, I guess it is unorthodox to have a solely JavaScript page? ```html p5.js example ``` that really is all I am doing. – nedsmith May 28 '19 at 21:44
  • @tadman okay the developer menu, got it. I have only started on JavaScript like 12 hours ago, but coming from other similar languages, I guess I thought it may be easy Ok, 30 mins, I can do that. – nedsmith May 28 '19 at 21:47
  • `mysqli` can do what you need, so it's fine for now. PDO is a better long-term solution because it's not MySQL specific, it works with Postgres, SQL Server, and others, which might have applicability to your work. One thing you'll quickly learn is rushed, half-assed code usually consumes more time than it saves since you'll almost always have to re-re-write it later. Do it correctly the first time and you won't have to go back and fix it later. Prepared statements take one more line, it's really not a big deal, and should be habitual and effortless to do. – tadman May 28 '19 at 21:47
  • @tadman its all a learning process, I wish I could write the best code the first time, but I'm about 5 gruelling days in to php and mysql running on xampp so it is all very puzzling for me. Also I must leave now, being awake until my eyes are heavy are not doing me any favours. – nedsmith May 28 '19 at 21:50
  • 2
    To be fair, it usually takes about two weeks of immersion to feel comfortable with any particular programming language, so don't feel too bad about being all confused five days in. – tadman May 28 '19 at 22:00
  • @tadman I've updated my question with a pretty big finding, could you take a look? – nedsmith May 29 '19 at 07:59
  • @Archer okay, I do apologise the HTML would have helped to show as it was the issue all along. :( – nedsmith May 29 '19 at 08:54

1 Answers1

0

First off in the HTML I did not know I needed to include

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

as I did not know I was using ajax, this is why the $ was undefined.

the updateLeaderboard function should look like this.

function updateLeaderboard() 
{
    alert("before");

$.post("process.php", { antNum, antRate },
    function(data)
    {
        alert(data);
    } );

    alert("after");
}

antNum and antRate are just vars which are previously defined.

and the process.php should look like

<?php

$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];

$con=mysqli_connect("localhost","root","pass","login");

mysqli_query($con,"UPDATE userdata SET `antNum`='$antNum' , `antRate`='$antRate' WHERE `player`='bob'");

?>

just swap bob out for the user in question.

PS. This was also a factor in helping me find the answer, by first allowing me to notice the $ was undefined.

nedsmith
  • 65
  • 1
  • 10
  • 1
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 29 '19 at 09:10
  • As a note, newer versions of jQuery ship without AJAX by default, so you often need the "complete" jQuery including it. – tadman May 29 '19 at 16:07
  • @tadman note taken. – nedsmith May 29 '19 at 17:11