Further Reading
If you want to read more abou t Web Storage, there’s quite an elaborate and beginner-
friendly coverage of the topic inside the b ook titled
HTML5 by Matthew MacDonald.
You may also want to look inside
JavaScript: The Definitive Guide by David Flanagan
for more elaborate coverage of the subject. Both books also cover oine applications
quite thoroughly.
Online, there’s a decen t article ava ilable at
www.sitep oint.com/an-overview-of-the-web-
storage-api
. For more comprehensive reading, though, you mig ht want to dig into
developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API.
B.3 Ajax
In the not-so-distant pa st, to retrieve new data from a web server, browsers ha d to
reload the whole web page. Not only was this slow due to the substantial amount
of data tha t ha d to be sent back and forth, but it was also uncomfor ta ble for a user
as the whole page disappeared and reappeared again even for updating the smallest
chunk of information from the server. Then , in 2005, the term Ajax was fashioned,
which o riginally stood for Asynchrono us JavaScript and XML. Ajax was first used
by Google in its magical Google Suggest, the other name for Go ogle’s auto-comp le te
functionality. It works so that when a visitor starts to enter letters in a search field, a
dropdown menu appears, sugg esting for the user possibly interesting terms. Although
the information is coming from the web server, the whole page stays put during the
operation. This is in fact the only—albeit extremely important—advantage of Ajax: it
permits a web page to be updated with information from the web server without ever
reloading the page. That way, web pages feel more responsive, greatly enh ancing the
user experience. How is tha t accomplished?
Ajax isn’t a technology in and of itself, but rather a n interaction o f more techn ologies
working together. You n eed Java Script, an XMLHttpRequ est object, and some server-
side scripting. The latter is, unfortunately, not covered in this book. Nevertheless, you
will ge t a basic idea of how Ajax works.
All the trac between web browsers an d servers is specified by the Hypertext Trans-
fer Protocol (HTTP), which is usually not contro lled by scripts but happens as a con-
sequence of user actions su ch as following a link or typing a URL. That said, the
XMLHttpRequest obje ct defines an A PI that allows a programmer to con trol HTT P
requests through JavaScript code. Basically, JavaScript uses an XMLHttpRequest ob-
ject to send a request to a web server, which responds by sen ding some d ata back.
JavaScript then collec ts the rec eived data, again through the XMLHttpRequest object,
and does with th em whatever it likes.
Before you can use the just-mentioned HTTP API, you must cr eate an XMLHttpRe-
quest object:
var myRequest = new XMLHttpRequest();
Now you’re ready to ma ke an HTTP request, which is made by calling the open()
B.3. Ajax 283
method of the XMLH ttpRequest object. Th e two r equired parts of the request are the
method and URL:
myRequest.open("GET", "greetings.txt");
The first a rgument of the open() method selects th e desired HTTP method and the
second one specifies the URL to which the request is to be addressed. The HTTP
method is most o ften GET or POST. In a nutshell, you can use GET to get data from
the ser ver, and POST to modify the server data (e.g., update a database). T here’s
also a technical dierence between both methods in that GET completely sp ecifies
the requested resource within th e URL, while POST expects additional data in the
request body. You have probably seen URLs like
.../index.php?search=holidays, wher e
there’s additiona l information added at the end of the regular URL (after the question
mark). This is the GET method’s way of specifying additional information needed
by a server-side script to process the request. For instance, if the web page requ ests
the server to run the
index.php script, w hich returns a list of pages containing some
specific keywords, the script also needs the keywords to search for (“holidays” in our
example).
Note that the URL given as a second a rgument in our example of the open() method
is a p la in text file and th e myRequest object will simply get the whole co ntent of
the file from the server. From a practical point of v iew, this is rarely useful, but it
nevertheless demonstrates the b asic procedure that is to be performed by a JavaScript
progr am to process an HTTP request. In reality, you would instead provide a URL
of a file containing some script that would intelligently process the HTTP request. A
very common example would be a PHP script commu nicating further w ith a MySQL
database.
After co mposing the request, all you have to do is send it to the server:
myRequest.send();
No matter what kind of technology sits on the other side of an HTTP request, you
more or less only need to provide the correct URL an d wait for the response after
sending the request. While it is possible to wait for the response synchronously, this is
not recommended since the send() meth od will block the browser until the re quest is
completed. A much better approach is to handle the HTTP response asynchrono usly.
To do that, you simply define the onreadystatechange handler of the XMLHttpRe-
quest object, which listens to readystatechan ge events:
myRequest.onreadystatechange = function() {
if (this.readyState == 4 && //Is the response complete?
this.status == 200) { //Was the request successful?
//Do something with this.responseText
}
};
284 Appendix B. Ways to Continue
Because the read ystatechange event can be fired (depending on the browser) at any
change o f the state of the request, you must check the readyState property of the
XMLHttpRequest object before processing the returned data. O nly if the value re-
turned by readyState is four, the response is complete and ready to process. It
is also important that the request be successful on the who le , which results in the
status property having the value 200 (“OK”). If the provide d URL doesn’t match
any of the resources on the server, then status returns the infamous e rror value 404
(“Not Found”).
If everything we nt OK, then the text r eturned from the server is to be found in the
responseText property of the XMLHttpRequest object, and from n ow on youre on
familiar ground. The following is a complete example which, when a button is clicked,
demands the
greetings.txt file through an HTTP request and places the received text
inside a <div> element:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax</title>
<script>
window.onload = function() {
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("myDiv").innerHTML =
this.responseText;
}
};
document.getElementById("myButton").onclick = function() {
myRequest.open("GET", "greetings.txt", true);
myRequest.send();
};
};
</script>
</head>
<body>
<form>
<div id="myDiv">This will change forever.</div>
<input type="button" value="HTTP GET" id="myButton">
</form>
</body>
</html>
Note that this exam ple will only work if you upload it to a web server because XML-
HttpRequest is designed to work with an HTTP protocol. You can conveniently use
the developm ent server that w e set up on page 37. If you test examples in this book
using a local file system, then all the URLs are r elative to
file:// instead of http:// ,
conseque ntly using a file instead of the requir ed HTTP proto col.
B.3. Ajax 285
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.54.7