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