27.10.2015 Views

AJAX and PHP

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Server-Side Techniques with <strong>PHP</strong> <strong>and</strong> MySQL<br />

A popular (<strong>and</strong> more powerful) alternative to using file_get_contents is a library<br />

called Client URL Library (CURL). You can find more details about CURL from<br />

http://curl.haxx.se, http://www.php.net/curl <strong>and</strong> http://www.zend.com/<br />

zend/tut/tutorial-thome3.php. For basic needs though, file_get_contents gets the<br />

job done nicely <strong>and</strong> easily.<br />

Let's try this out with some code. The functionality we want to implement is the same as in<br />

the previous exercise (get a r<strong>and</strong>om number <strong>and</strong> display it), but this time it will work with<br />

all browsers.<br />

Time for Action—Using a Proxy Server Script to Access Remote Servers<br />

1. In the foundations folder, create a subfolder named proxyping.<br />

2. In the proxyping folder, create proxyping.html:<br />

<br />

<br />

<br />

Practical <strong>AJAX</strong>: Accessing Remote Server through Proxy <strong>PHP</strong><br />

Script<br />

<br />

<br />

<br />

Server, tell me a r<strong>and</strong>om number!<br />

<br />

<br />

<br />

3. In the same folder create proxyping.js. Note that this file is similar to ping.js, <strong>and</strong><br />

the new bits are highlighted. (We removed the bits that h<strong>and</strong>le Mozilla security from<br />

process(), changed the server address in the header, removed the num parameter<br />

because in this scenario we'll only request one number at a time, <strong>and</strong> added an errorh<strong>and</strong>ling<br />

measure.)<br />

// holds an instance of XMLHttpRequest<br />

var xmlHttp = createXmlHttpRequestObject();<br />

// holds the remote server address <strong>and</strong> parameters<br />

var serverAddress = "proxyping.php";<br />

var serverParams = "&min=1" + // the min number to generate<br />

"&max=100"; // the max number to generate<br />

// creates an XMLHttpRequest instance<br />

function createXmlHttpRequestObject()<br />

{<br />

// will store the reference to the XMLHttpRequest object<br />

var xmlHttp;<br />

// this should work for all browsers except IE6 <strong>and</strong> older<br />

try<br />

{<br />

// try to create XMLHttpRequest object<br />

xmlHttp = new XMLHttpRequest();<br />

}<br />

catch(e)<br />

{<br />

// assume IE6 or older<br />

var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",<br />

"MSXML2.XMLHTTP.5.0",<br />

86<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!