J'utilise actuellement un script javascript (startGame) qui se lance au moment du click sur un bouton. StartGame réalise 2 actions:
1) Il lance un script PHP pour créer et initialiser des variables de sessions
2) Il effectue une redirection
Le script PHP seul à l'air de bien marcher (lorsque je l'inclus dans ma page au lieu de le lancer via javascript, les variables de session sont bien crées).
Mais quand il est lancé via startGame, j'ai l'impression qu'il n'a pas le temps de travailler. Du coup mes variables de session ne sont pas crées et tout merdoie.
J'aimerais savoir si il y-a quelque chose que je fais de travers ou pas. J'ai déjà tenté de mettre un sleep dans startGame mais ça ne résout pas mon problème.
Merci beaucoup
Voici mon code:
function startGame()
{
generateRequest("empty", phpGameInit);
self.location.href=gameMiddlePage;
}
function generateRequest(callBackFunction, phpScript, toPost)
{
var xmlHttp = generateXmlhttp();
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState==4 && (xmlHttp.status == 200 || xmlHttp.status == 0))
{
if(callBackFunction!="empty")
{
callBackFunction(xmlHttp.responseText);
}
}
}
if(toPost)
{
xmlHttp.open("POST",phpFolder.concat(phpScript),true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
for(var i=0; i<toPost.length; i++)
{
xmlHttp.send(toPost[i]);
}
}
else
{
xmlHttp.open("GET",phpFolder.concat(phpScript),true);
xmlHttp.send(null);
}
}
<?php
session_start();//must be in first position. allows to use session variables
include_once "phpFunctions.php";
//Variables to be used in coding for easier changes
$col_game_time="game_time";
$col_game_nb_questions="game_nb_questions";
$col_game_level="game_free_answers_level";
$col_game_questions="game_free_answers_questions";
$all_game_table="game";
$game_url="http://tests_vh/TestAjax/game_free_answers.php";
$game_table="game_free_answers";
//Session variables that can be used on every user pages
$_SESSION["startTime"]=date('U');
$_SESSION["currentLevel"]=1;
$_SESSION["idGamer"]=1;
$_SESSION["idGame"]=2;
$_SESSION["lineQuestionInTable"]=-1;
$_SESSION["nbCorrectAnswers"]=0;
$_SESSION["nbAnswers"]=0;
$_SESSION["nbQuestionsAsked"]=0;
//Data base connection to update variables
$sql="SELECT * FROM " . $all_game_table . " WHERE id = '". $_SESSION["idGame"] ."'";
$queryResult=executeQuery($sql);
while($row = mysql_fetch_array($queryResult))
{
$_SESSION["nbQuestions"] = $row[$col_game_nb_questions];
$_SESSION["nbTime"] = $row[$col_game_time];
}
$sql="SELECT * FROM " . $game_table . " WHERE ".$col_game_level." = '".$_SESSION["currentLevel"]."'";
$queryResult=executeQuery($sql);
while($row = mysql_fetch_array($queryResult))
{
$questions[]=$row;
}
$_SESSION["questionsPorfolio"]=$questions;
?>