Pregunta

I am building a game on html5(phaser js) for which i need to build a leaderboard. the code snippet is this:

restart_game: function() {  
// Start the 'main' state, which restarts the game
//this.game.time.events.remove(this.timer);  
    //this.game.time.events.remove(this.timer2);  
    //this.game.state.start('main');
    var string="score.php?score="+this.score;
    window.open(string);
},

in the window.open function i wish to pass the value of score to another page where i will ask for the player's name and then insert both the score and the name to the database. But i am having trouble passing the score value across three pages. How can i do this? Do I need AJAX or just PHP and Javascript is sufficient?

¿Fue útil?

Solución

Can you use browser cookie? you can save score value in cookie and access it whenever you need? Read this on how to use cookies link https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

To save to cookie like this:

document.cookie="score=54; expires=Thu, 18 Dec 2013 12:00:00 GMT";

In PHP you can read cookie

if(isset(($_COOKIE['score'])) {
    $score = $_COOKIE['score'];
}

To Read cookie in JS:

var score = document.cookie;

Otros consejos

You may use the session variable for keeping the variable in the memory and it will be accessible untill your session is alive.

<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
    $session = eval("return {$_POST['session']};");
    if (is_array($session)) {
        $_SESSION = $session;
        header("Location: {$_SERVER['PHP_SELF']}?saved");
    }
    else {
        header("Location: {$_SERVER['PHP_SELF']}?error");
    }
}

$session = htmlentities(var_export($_SESSION, true));
?>

For more information look here Here

Find jQuery

restart_game: function() {  
  var score = this.score;
  $.ajax({
    url: 'save_score.php',
    data: {score: score},
    method: 'POST'
  }).done(function() {
    window.location = "other_page.php";
  });
},

save_score.php

session_start();

if(isset($_POST['score']) && strlen($_POST['score']) > 0) {
  $score = intval($_POST['score']);
  $_SESSION['score'] = $score;
}

other_page.php

session_start();
var_dump($_SESSION);

You can use the $_SESSION variable in php to keep track of user related data in a session. It requires cookies.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top