1

For my project I need to do the following:

  1. User presses his Mouse on the canvas (html page)
  2. JavaScript function saves the coordinates of the points that have been pressed
  3. Send this info to a PHP script
  4. PHP script adds this data to MySQL database
  5. Other coordinates are put into JSON and sent to back to the client and presented on the same canvas

Now, I have looked into the problem of step 3 (which is something I don't know how to do). There are different ways, I have selected these two:

  1. Using Ajax
  2. HtmlRequest (answer 3)

Which would be the best way to choose in my situation? Is there yet a better / right way to do it?

Community
  • 1
  • 1

1 Answers1

1

I wouldn't say there is necessarily a "right" way to do it, however there are some good ideas you can follow. One of those ideas is to use HTTP REST verbs: use POST for "create" operations and GET for "read" operations. Given that, you should do an AJAX POST request to your server and pass the coordinates via POST parameters.

// will use this to turn an object into a url encoded string
var serializeObject = function(obj) {
  var output = '';
  for(var attr in obj) {
    if(obj.hasOwnProperty(attr)) {
      output += attr + '=' + obj + '&';
    }
  }
  return output.slice(0, -1);
};
var url = 'http://www.example.com/save.php';
// you need to serialize your data into key value pairs like the following
var exampleCoords = {
  x: 10,
  y: 20,
  z: 30
};
// postData will be x=10&y=20&z=30
var postData = serializeObject(exampleCoords);

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", postData.length);
request.setRequestHeader("Connection", "close");

// this function gets called when the request changes
request.onreadystatechange = function() {
    // request was successful
    if(request.readyState == 4 && request.status == 200) {
        alert(request.responseText);
    }
}
request.send(postData);

Using jQuery you could simplify your code quite a bit (though it's pretty much doing the exact same thing behind the scenes):

var url = 'http://example.com/save.php';
var coords = {
   x: 10,
   y: 20,
   z: 30
};
$.post(url, coords).then(function(response) {
   console.log(response);
});

You can access those variables in PHP using $_POST['x'], make sure you sanitize this data (htmlentities, etc.) before using it in MySQL.

For the record, AJAX and XMLHttpRequest are different names for the same thing, AJAX is just referring to Asynchronous Javascript and XML (as in XMLHttpRequest), XMLHttpRequest is the built-in object you use to perform AJAX requests

Rob M.
  • 35,491
  • 6
  • 51
  • 50