0

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 accomplish such a thing? Or is there a better way?

Thanks!

1
  • 3
    Not possible. You'll need a server side language. Commented Oct 14, 2012 at 20:52

3 Answers 3

5

In 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Quentin, I'll start reading up on Ajax and HTTP Requests
2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.