Understanding Ajax: Using JavaScript to Create Rich Internet Applications
[next]
Understanding Ajax: Getting Started
The foundation that makes Ajax possible is the communication layer with the server. The most complete option for performing this communication is the JavaScript XMLHttpRequest
object. If XMLHttpRequest
is not suitable to you, hidden IFrame
s and cookies can also be used. We will examine both options later in this chapter.
This chapter introduces you to the XMLHttpRequest
object, showing you how to work around its implementation differences between browsers. After that, we make some actual page requests, both in a synchronous fashion and in an asynchronous fashion. This chapter finishes with some various fallback approaches that can be used if a browser doesn’t support XMLHttpRequest
, including how to use IFrame
s and cookies as your communication channel.
2.1 XMLHttpRequest
Overview
Originally, Microsoft designed XMLHttpRequest
to allow Internet Explorer (IE) to load XML documents from JavaScript. Even though it has XML in its name, XMLHttpRequest
really is a generic HTTP client for JavaScript. With it, JavaScript can make GET
and POST HTTP
requests. (For POST
requests, data can be sent to the server in a format of your choosing.) The main limitations to XMLHttpRequest
are due to the browser security sandbox. It can make only HTTP(S) requests (file URLs, for example, won’t work), and it can make requests only to the same domain as the currently loaded page.
The security limitations of XMLHttpRequest
do limit the ways in which you can use it, but the trade-off in added security is well worth it. Most attacks against JavaScript applications center around injecting malicious code into the Web page. If XMLHttpRequest
allowed requests to any Web site, it would become a major player in these attacks. The security sandbox reduces these potential problems. In addition, it simplifies the programming model because the JavaScript code can implicitly trust any data it loads from XMLHttpRequest
. It can trust the data because the new data is just as secure as the page that loaded the initial page.
Despite the fact that XMLHttpRequest
provides only a small API and just a handful of methods and properties, it has its differences between browsers. These differences are mainly in event handling and object instantiation (in IE, XMLHttpRequest
is actually an ActiveX object), so they aren’t hard to work around. In the following overview of the XMLHttpRequest
API, the Mozilla syntax for XMLHttpRequest
instantiation is used. If you want to run the examples in IE, you need to replace new XMLHttpRequest();
with either new
ActiveXObject("MSXML2.XMLHTTP.3.0");
or the full cross-browser instantiation method shown in the "Cross-Browser XMLHttpRequest
" section of this chapter.
XMLHttpRequest
is the most-used method for Ajax communications because it provides two unique features. The first feature provides the ability to load new content without that content being changed in any way, which makes it extremely easy to fit Ajax into your normal development patterns. The second feature allows JavaScript to make synchronous calls. A synchronous call stops all other operations until it’s complete, and while this isn’t an option that is usually used, it can be useful in cases in which the current request must be completed before further actions are taken.
2.1.1 XMLHttpRequest::Open()
The open
method is used to set the request type (GET, POST, PUT
, or PROPFIND
), the URL of the page being requested, and whether the call will be asynchronous. A username and password for HTTP authentication can also be optionally passed. The URL can be either a relative path (such as page.html
) or a complete one that includes the server’s address (such as https://blog.joshuaeichorn.com/page.html). The basic method signature is:
open(type,url,isAsync,username,password)
In the JavaScript environment, security restrictions are in place. These security restrictions cause the open
method to throw an exception if the URL is from a different domain than the current page. The following example uses open
to set up a synchronous GET
request to index.html
:
1 var req = new XMLHttpRequest(); 2 req.open(’GET’, ’index.html’, false); 3 req.send(null); 4 if(req.status == 200) 5 alert(req.responseText);
2.1.2 XMLHttpRequest::Send()
The send
method makes the connection to the URL specified in open
. If the request is asynchronous, the call will return it immediately; otherwise, the call will block further execution until the page has been downloaded. If the request type is POST
, the payload will be sent as the body of the request that is sent to the server. The method signature is:
When you make a POST
request, you will need to set the Content-type
header. This way, the server knows what to do with the uploaded content. To mimic sending a form using HTTP POST
, you set the content type to application/x-www-form-urlencoded
. URLencoded
data is the same format that you see in a URL after the "?". You can see an example of this encoded data by making a form and setting its method to GET
. The following example shows a synchronous POST
request to index.php
that is sending a URLencoded
payload. If index.php
contains <?php var_dump($_POST); ?>
, you can see the submitted data translated as if it’s a normal form in the alert:
[next]
URL: