Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and Javascript working together

It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.

I've seen it done with Chat rooms but not sure how it works.

like image 413
Tyler Hughes Avatar asked Jun 30 '12 05:06

Tyler Hughes


2 Answers

We mostly use Ajax, which consists in a client-side Javascript code that calls a server-side page, with out leaving the page.

Here's an example that will get the displayed content of a page, using the GET method (JSFiddle):

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onreadystatechange = function(){
    if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
        console.log(this.responseText);
    }
}
xhr.open('GET','myPHPPage.php?foo=foo&bar=bar',true);
xhr.send();

And here using the POST method (JSFiddle):

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
var data = 'foo=foo&bar=bar';
xhr.onreadystatechange = function(){
    if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
        console.log(this.responseText);
    }
}
xhr.open('POST','myPHPPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length',data.length);
xhr.send(data);

Note that here we use the setRequestHeader method to change the headers of this HTTP request and, in this case, to change the Content-type and the Content-length (this header has a default value of 4096 bytes). Also, the setRequestHeader method must be called after the open method.

These links should help you:

https://developer.mozilla.org/en/Ajax

http://code.google.com/intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html

like image 121
Danilo Valente Avatar answered Nov 13 '22 16:11

Danilo Valente


Yes it's incredibly common. Read up on Ajax.

like image 31
Bob Davies Avatar answered Nov 13 '22 16:11

Bob Davies