Skip to content

Save click co-ordinates to a file on the server

I am currently outputting the user click co-ordinates to the console and saving the file manually. I am trying to output these coordinates to a json file on the server which will be updated every time the user clicks.

<script type="text/javascript">
var clickX;
var clickY;
  onmousemove = function(e){
    clickX = e.clientX;
    clickY = e.clientY;
    console.log('X: '+clickX+', Y: '+clickY);

    var clicks = {"x": "clickX", "y": "clickY"}
    
    $.ajax({
      type : "POST",
      url : "save_json.php",
      data : {
          json : JSON.stringify(clicks)
      }
  });
  }
</script>

<?php
$myFile = "clicks.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_GET["data"];
fwrite($fh, $stringData);
fclose($fh)
?>

However I am not managing to do so with my current code.

Answer

There are quite a few things that you’re probably missing here. Firstly the ajax call makes a POST request but you’re looking for the data in the $_GET array, so lets make the first change of the ajax request to make a GET request over here. That makes your ajax call look as follows

$.ajax({
        type : "GET",
        url : "save_json.php",
        data : {
            json : JSON.stringify(clicks)
        }
    });

Similarly, another issue is in var clicks = {"x": "clickX", "y": "clickY"} where instead of passing clickX and clickY parameters you’re passing them as strings "clickX" and "clickY". This can be fixed by changing it to

var clicks = {"x": clickX, "y": clickY};

Lastly the event that you’re using onmousemove records each and every single move made by the cursor and not really the clicks, based on the variable names and the question I believe you want the clicks, the event you’re looking for is onmouseup

Now the javascript code looks as follows with the corrections made

<script type="text/javascript">
var clickX;
var clickY;
onmouseup = function(e){
    clickX = e.clientX;
    clickY = e.clientY;
    console.log('X: '+clickX+', Y: '+clickY);

    var clicks = {"x": clickX, "y": clickY};

    $.ajax({
        type : "GET",
        url : "save_json.php",
        data : {
            json : JSON.stringify(clicks)
        }
    });
}
</script>

Now coming to the PHP part, you need to modify the script as follows, the data that you’re sending gets sent as array(1) { ["json"]=> string(17) "{"x":269,"y":125}" } on every click, the list item you’re looking for is "json" and not "data", So making the correction to the script as follows

<?php
$myFile = "clicks.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_GET["json"];
fwrite($fh, $stringData);
fclose($fh)
?>

With the right permissions on the clicks.json file, you should be able to make an entry in the file which will look as follows

{"x":798,"y":123}

and will keep getting overwritten after every click because of the w mode used in fopen()