I have a JS game (on a HTML page) and I want to create a log file every time someone plays, so that I can record thing like their score, and the amount of time they played.
I know that JS is a client side language, so how can I go about saving a file to a server? Is it possible to insert some .php in my JS to acplish such a thing? Or is there a better way?
Thanks!
I have a JS game (on a HTML page) and I want to create a log file every time someone plays, so that I can record thing like their score, and the amount of time they played.
I know that JS is a client side language, so how can I go about saving a file to a server? Is it possible to insert some .php in my JS to acplish such a thing? Or is there a better way?
Thanks!
Share Improve this question asked Oct 14, 2012 at 20:51 BloonsTowerDefenceBloonsTowerDefence 1,2042 gold badges20 silver badges43 bronze badges 1- 3 Not possible. You'll need a server side language. – Pekka Commented Oct 14, 2012 at 20:52
3 Answers
Reset to default 5In order to send data to the server, you must make an HTTP request. (Making an HTTP request from JavaScript without leaving the page is known as Ajax). For this type of situation, this is usually done using the XMLHttpRequest object. You then need a server side program (which you could write in PHP) to process the request and save the data. To avoid having to worry about file locking and the like, you should consider using a database instead of a flat file.
I do it more or less like this in my projects (here the basics, of course more advanced depending on project, error checking and so on)
javascript
function doLog(somedata) {
$.ajax({
url: "ajax_log.php",
//data, an url-like string for easy access serverside
data : somedata,
cache: false,
async: true,
type: 'post',
timeout : 5000
});
}
serverside
most of the times I use a class that inserts each element from somedata as rows in some log-tables, like a table log
with id and timestamp, and a table logParams
, with id and param / value. But that is for statistically porpuses. Other times it is only nessecary to log somedata in a file
<?
$file="log.txt";
$text=serialize($_POST);
$fh = fopen($file, 'a') or die();
fwrite($fh, $text."\n");
fclose($fh);
}
?>
So it is very easy to make a log-system executed by JS, and not hard to implement almost anything in it
You'll most likely have to make an AJAX call to the server. From there, your PHP code, or whatever server-side scripting language you want to use, will be responsible for creating the log file.