Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^280) CHAPTER 18 ■ AJAX AND JSON
Some Ajax Projects
To get the most from the previous theory, you’ll want to create a couple of simple applications.
The following two examples demonstrate common GET and POST requests.


GET Requests


When dealing with client/server communications, an effective way to test your data transport
and the interaction of all the components is to create a really simple time-fetch application.
This application will send out a request whenever a link is clicked, and the XHR object will get
a response from the server indicating the current server time.
This example has two key components: a client-side JavaScript script and a server-side
PHP script. The client-side XHR object is restricted to operating within a single domain. This
means an XHR request may contact only the exact same domain as the HTML file that included
the script, so creating an HTML file on your desktop that points to your PHP-enabled web
server simply won’t work. Both the open() URL and the client HTML file must be served from
the exact same domain.
Start by creating a PHP script on your server, as shown in Listing 18-6.

Listing 18-6. A PHP Time Ping-Pong (time.php)

<?php
echo json_encode(microtime(true));

Next, create a client-side script, following Listing 18-7 as a guide.

Listing 18-7. Client-Side Ajax (ajax.htm)

<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">

function getXHR() {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
return req;
}

function getServerTime() {
xhr = getXHR();
rand = Math.random(1);

McArthur_819-9.book Page 280 Friday, February 29, 2008 8:03 AM

Free download pdf