Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 18 ■ AJAX AND JSON^281

//CHANGE THIS LINE – DOMAINS MUST MATCH!

url = "http://example.com/time.php?id="+ rand;

xhr.open("GET", url, false);
xhr.send();
json = xhr.responseText;
time = json.parseJSON();
div = document.getElementById("jsonData");
div.innerHTML = time;
}
</script>
</head>
<body>
<a href="#" onclick="getServerTime()">Get Server Time</a>
<div id="jsonData"></div>
</body>
<html>

■Note In the client-side script in Listing 18-7, you will see that there is an added id= get parameter set
to a randomized number. This is to avoid HTTP caching of the Ajax URL. You could also achieve the same
result by sending the correct cache headers with the response to prevent caching of the open URL.

In this script, you get a reference to the XHR object; set the open() parameters 'GET', url,
and synchronous (blocking) mode; and then call send() to get the data. When the send() call
returns, the responseText property will be ready. The JSON-encoded data can be retrieved
from this property, decoded, and turned back into a real value. Once the real value is obtained,
it is written to the screen.
Click the hyperlink a few times. You should get a different time (in microseconds) returned
with each click.

■Caution If you received an access denied client-side error, the most likely reason is that the domain used
to load the ajax.htm script is not the exact same as is set in the open() URL parameter. Even the difference
between http://www.example.com and http://example.com will result in an access denied error, so
take care to make sure they both match exactly.

POST Requests


POST requests in Ajax are somewhat more complicated that GET requests, as they require you to
set the proper form HTTP header. To demonstrate their use, you will create a search box that
will list suggestions from an array of server-side data. The recipe for this application is to use

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

Free download pdf