WEB_UI WEB_UI - 11 months ago 44
Javascript Question

What is the most efficient way for PHP and JavaScript to transfer data?

I've seen many different approaches for transferring javaScript and PHP data, but I question the efficiency and precision. What I mean by that is, say for example you have a javaScript platformer (game) that has 10 levels. You have many users with each of them having/owning a different account. You want to make this game, so that when a user closes the browser tab or saves and wants to play it later; he/she doesn't have to restart from level 1. Instead you want it so that when the user saves, you store the current level number that the user saved on, in a mySQL database in his or her account data. Now, the only problem being, is that the number of levels the user completed, is stored in a javaScript variable, but you need to somehow transfer/get that variable in PHP in order to do so, how would you do that? I've seen document.write (<set php variable here>), but I don't think that is the most efficient way to approach this.

Answer Source

My approach would be to save the finished level via an AJAX call after the user has successfully finished a level. That way you dont have to worry about the user closing the browser, ie if he does and he has not finished the level then he must repeat the last level he did not finish.


JS script:

  method: "POST",
  url: "update_finished_level.php",
  data: { user_id: "1", level_finished: "4", some_other_parameter: "some value" }
.done(function( msg ) {
    if(msg == 1) {
        // OK
    } else {

PHP script (suppose you are using mysqli to connect to your DB):

$link = mysqli_connect("", "my_user", "my_password", "my_db");

if ($link->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);

if($mysqli->query("UPDATE user SET level_finished = " . $_POST['level_finished'] . " WHERE user_id = " . $_POST['user_id']) === TRUE) {
    echo 1;
} else {
    echo 0;

BEWARE: You have to escape any output that you get from a user so at least use the mysql_real_escape_string function, which BTW isnt safe anymore.

I would suggest you use something like the PHP PDO library: http://php.net/manual/en/book.pdo.php. There are many tutorials out there how to use it with prepared statements.