I have a javascript game running within a HTML5 canvas. Now I'd like to pass on a variable that is stored in an object in PHP to my program. What I'd like to have would be a function in my js like getVariable = function(){script that gets the variable from PHP and returns it as a string}
Any hints?
@Valentin - simply use javascript ajax call(Or jquery call if you like) to get the values from the php script. If your game has different values for different players you can start a session and persist the values across many calls to the script.For example -
Let say you want to get the health of the player from player.php which looks like
session_start();//start the session
if(!isset($_SESSION['health']))
$_SESSION['health'] = $var;//If there is no value for player health in the session
//initialize the default value
switch($_GET['x']){
case 'health' :
echo $_SESSION['health'];
break;
default :
echo $var;
break;
}
?>
and the corresponding pure javascript would be -
var health;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
health=xmlhttp.responseText;
}
}
xmlhttp.open("GET","player.php?x=health",true);
xmlhttp.send();
You could do the same in a much simpler fashion using the awesome jQuery -
var health;
var reqData=["x" : "health"];
var xhrObj = $.get("player.php",x)
.done(function( response ) {
health=response;//The echo text from server
})
.fail(function() {
alert('error');
});
You can learn more about jquery and ajax here -->
www.w3schools.com/ajax/ for the ajax tutorial
Javascript and the browser don't care what language you're using on your server to generate the HTML/JS, all they care about is what is generated in the end.
To do what you're thinking, you'd have 2 ways to do it: