-1

I am new to php and javascript. I am trying to post some variables to another php file using ajax. From my main php file, I have a javascript setInterval calling a function to send data every 500ms. The function called is:

function UpdateDB(xval, yval) {
     TimeCount++;         
    //   console.log(xval, yval, TimeCount);
     $.ajax({
       type: "POST",
       url: "ud.php",
       data: { x: xval.toString(), y: yval.toString(), t: TimeCount.toString() }
    });
     return TimeCount;   
    }
   

This function runs fine as I get the console log data (if I uncomment). I can also see in developer tools (chrome) in the network, the file ud.php appears to be run, but I do not believe this is the case. ud.php is a simple file that updates data in a table:

//<script type="text/javascript">console.log("ud");</script>

<?php

if (!isset($_SESSION['id'])) {
  exit();
}
//require "includes/dbh.inc.php";
$sql = "UPDATE units SET JoyX='$x', SET JoyY='$y', SET JoyTimeStamp='$t', WHERE SN='$serial'";
//$sql = "UPDATE units SET JoyTimeStamp='$t' WHERE SeralNumber='$serial'";
mysqli_query($conn, $sql);
mysqli_close($conn);
exit();
?>

I wrote the commented out line at the top to see if the file was run, but when uncommented it does not log to the console. I suspect my ajax query is incorrectly formatted, but again I am new to this and have searched for the last few days to find an answer without success. Thanks for any help.

  • Does the network tab say its getting a 500 response from the server? That php snippet can suggest many issues... is there more too it? – IncredibleHat Sep 22 '20 at 13:34
  • If you see that `ud.php` is called in the network tab, then it's being called. The script tag in the PHP file will never console log anything. Javascript in an Ajax response doesn't get executed. When you make an Ajax call, the response of that call is just returned as a string, not caring about the contents so the browser doesn't parse the response in any way. Add a success-callback to your ajax code and console log the response instead. Then you can see all the errors that PHP throws at you for the above PHP code (which should be a few errors and warnings) – M. Eriksson Sep 22 '20 at 13:35
  • 1
    Also that bit of JS you have in the php, wouldn't necessarily execute because your ajax call does not have a `success` call back to kick jquery into processing the return data. – IncredibleHat Sep 22 '20 at 13:35
  • Did you start the session in ud.php using ```session_start()``` at the top? – Sameer Kumar Jain Sep 22 '20 at 13:36
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 22 '20 at 14:55
  • Then it is being called, thanks for confirming. I guess I am struggling to find a way to output debug data. I am sending 3 values to ud.php, those values are then used to update a table, but the table is not being updated. I already have a session open, so I'm unsure why the table is not updated. – Dave Everett Sep 22 '20 at 15:02

1 Answers1

1

The PHP file is successfully being invoked, you just have an invalid expectation of the result. Check the network tab in your browser's debugging tools. Are there any error codes in the request/response? Does the response contain the information you expect? If so then it's working.

The question is... What are you doing with that response?

The AJAX operation by itself doesn't do anything with the response. But it gives you an opportunity to do something with it. For example, in the jQuery .ajax() call you're using, there's a success callback which gets invoked on a successful result. So you can do something like this:

$.ajax({
   type: "POST",
   url: "ud.php",
   data: { x: xval.toString(), y: yval.toString(), t: TimeCount.toString() },
   success: function () {
      console.log("ud");
   }
});

So instead of trying to return new JavaScript from the server, you write the JavaScript here that you want to invoke when the operation successfully completes. (Alternatively you can use an error callback for a failed response.)


If you want to send data back from the server, anything you echo to the response would be available as the first argument to the success function. For example, if you do this on the server:

echo "ud";

Then in the success callback you can show that text:

success: function (result) {
    console.log(result);
}
David
  • 208,112
  • 36
  • 198
  • 279
  • I am not doing anything with the response. As a new update will be made every 500ms, I don't mind if I were to miss one. I could use a response to check during debug that something has happened, but I have been relying on refreshing the table to see if the values have changed. At the very least the TimeCount value should be different in the table as it is incremented each time the function is called even if the other values xval and yval have not changed. – Dave Everett Sep 22 '20 at 15:05
  • @DaveEverett: Since the AJAX request is working, your next step would be to debug the PHP code. For example, the SQL query appears to be relying on variables which are not defined and then no error checking is performed. Take a look at `mysqli_error` to check for errors. (And definitely [start here](https://stackoverflow.com/q/60174/328193) for fixing your query.) Output or log your SQL query itself before executing it to see what you're actually trying to execute. Whatever the issue ends up being, it may be worth a new Stack Overflow question. – David Sep 22 '20 at 15:13
  • Thanks to everyone for the advice, I have plenty to consider. – Dave Everett Sep 23 '20 at 11:39