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 -->
jQuery API
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:
Print the contents of the variable to the page when initially generating it.
Use an AJAX call to a script on your server that echo's the value, then parse it in JavaScript. If you do this, though, you'd have to use the session or a database, or another means of keeping state between pages.
Related
I am currently trying to refresh my page title every 10 seconds to ensure that the song info changes here:
But after the song changes, I am left with the same page title:
My JavaScript setInterval function isn't working correctly.
Here's my code (what should have worked):
<script type="text/javascript">
function songToTitle() {
document.title = "BDR | <?php echo $radio_info['now_playing']; ?>";
}
songToTitle();
setInterval(songToTitle, 10000);
</script>
<title>BDR | Loading Song Title...</title>
I don't really know what's up here.
It imports the song name correctly, but does not refresh.
Can anyone help me with this?
EDIT:
I tried using this too:
<script type="text/javascript">
function songTitle(){
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)
{
document.title.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.x86cam.com/wp-content/plugins/songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
It won't even load the title.
You are refreshing a static piece of information. To get new information you must use AJAX.
PHP is loaded before your browser opens it.
In other words...
<?php echo $radio_info['now_playing']; ?>
turns into
'Song Name'
so when Javascript looks at it, it only sees Song Name and is none the wiser.
AJAX Reference - complete API reference with examples down the page for you to fork off of. Your responding page also needs to be programmed to respond correctly. Usually I suggest JSON but this you can probably just use a text transfer since it's so little data.
You can send the data using POST and the PHP file can have something like this at the top:
<?php if ($_POST['songcheck'] === true) { echo $songName; return; }; ?>
PS - refreshing every 10 seconds isn't very efficient. When the song is loaded, use the song length +2 or +3 seconds for the timer instead. Much better :)
You can't use that php code in there, it's not going to execute when the function runs because PHP ran at the server, the code is now running in your browser, so once the song changes, that string is still going to be the exact same string it was when the browser asked your server for that .html file
You'll have to ask your server what the current title is using an xhr call ever X seconds and then refresh the title based on that.
I guess you should do an ajax call or listen to a some event to retrieve updated song title. The document.title = "BDR | <?php echo $radio_info['now_playing']; ?>"; string is generated on initial page load.
Okay. I figured it out.
I put this in my code:
<script type="text/javascript">
function songTitle(){
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)
{
document.title=xmlhttp.responseText;
}
}
xmlhttp.open("GET","songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
In my songTitle.php, it requests the song name from the Icecast server and displays only that.
Whenever the song changes now, it also changes the title.
I just had to integrate an XMLHTTPRequest like I did with how I displayed the song info on the page.
I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.
I want to create a Login-Screen in HTML where the user can fill out his username and password. After that he sends the Data with a submit to the server which validate the data. If the Login is correct he sends back a message in JSON format with an id, like this:
{"id":"37"}
Now my question: How can i get this information in Javascript? I want to check the id and, if it's OK, redirect the user to a new HTML screen.
I'm working with PhoneGap to create a Android Application, so the only things I can use are HTML, CSS and JavaScript. To send the POST i use the HTML <form> tag, not a special JavaScript. If I test it in Firefox it works, I fill out my Username and Password and then the Message with the id is shown. Now I want to react on this response with JavaScript. Can somebody help me?
AJAX Code:
function loadXMLDoc() {
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) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST",url,true);
xmlhttp.send(login);
A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.
var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a function that will be called for every key and value at every level of the final result.
now access the id property like myObject.id
on $(document).ready(function() in index.php, the below AJAX is executed, running the file getData.php:
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)
{
document.getElementById("dataSuccess").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getData.php",true);
xmlhttp.send();
In the getData.php file, data is gathered from MySQL and put in JS-arrays:
var guestData = new Array("<? for ($j=0;$j< sizeof($guestData);$j++) { print ($guestData[$j]); ?>","<?php } $j = $j+1; ?>");
And finally, store the data in my js arrays into LocalStorage:
var guestDataCols = new Array();
guestDataCols = guestData[0].split(",")
var arrayIndex=0;
for(arrayIndex=0;arrayIndex<guestData.length-1;arrayIndex++)
{
localStorage.setItem(arrayIndex, guestData[arrayIndex]); // storing
}
EVERYTHING works! But the problem is that my AJAX code doesn't seem to run through the entire getData.php file since LocalStorage in yet empty after the php-file is executed via AJAX. However (and this is a big one), if I simply refresh getData.php in another window, data is stored perfectly and evernything works. I've also tried using jQuery for this as suggested in another Stack Overflow question
$('#dataSuccess').load('getData.php'); //instead for the AJAX code
but with the exact same and somewhat mediocre result. So my questions is, why isn't the AJAX script running the entire php file and HENCE, why is no data stored in LocalStorage?
JavaScript on an HTML page is not run when called by an XMLHttp request. The browser doesn't parse the pages that JavaScript receives over XMLHttp requests and therefore does not run the JavaScript. You would have to output to the browser for it to be run. Your best bet would be do have the PHP return the data you need and then extract it from the XMLHttp request. For example, the getData.php could return a JSON string containing the data you need. Then on the page with the XMLHttp request, you could parse that JSON string and save it to the localStorage on that page.
I think you're looking for jQuery.getScript
I knew exposing web service is a obvious option, is there any other quick method?
That question is too general to answer in any sort of useful way. But that said: a lot of people are using JSON for data interchange these days. If you're willing to use jQuery or another library, it's extra-easy to use AJAX to grab JSON and act on it. Otherwise, I imagine it's not that difficult with plain JavaScript either.
Your question is very vague, so I will try to answer it before some trigger happy mod closes it (sweet sweet reputation points!)
One option is Ajax. This lets you ask the server for information using PHP scripts
Client (HTML/Javascript)[1]:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(){
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){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
It looks intimidating, but all you're doing is saying GET me the stuff in ajax_info.txt on the server, and when you do get it (onreadystatechange) write it out for me (console.log).
You can use the above and tweak it so instead of reading a text file it reads a PHP file. That way you could ask it to execute a PHP script, which reads the contents of the server (server type, database elements...) and returns it to the user. Here is How I do it (I use Dojo instead of pure javascript)
On the Client:
dojo.xhrGet({
url: 'getUser.php',
handleAs: "text",
content: {
title: "Mr. "
},
load: function(data) {
console.log(data);
}
}
on the server ('getUser.php'):
<?php
echo $_GET['title'] . get_current_user();
?>
The server will concatenate 'Mr.' with the current user and return it to the client which will print out something like so
Mr. www-data
Finally another way is to embed directly into javascript/html so when you load the page, the server automatically updates the source code (warning, this requires quite a bit of tweaking)
index.html/index.php [2]:
<html>
<head></head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>