Getting Started: Ajax

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 IFrames 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 IFrames 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 http://www.miraclestudios.us/)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:

send(payload)<br />

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:

1

var req = new XMLHttpRequest();

2

req.open(’POST’, ’index.php’, false);

3

req.setRequestHeader(’Content-type’,

4

’application/x-www-form-urlencoded;charset=UTF-8;’);

5

req.send(’hello=world&XMLHttpRequest=test’);

6

if(req.status == 200)

7

alert(req.responseText);

var req = new XMLHttpRequest();<br /> req.open(’POST’, ’index.php’, false);<br /> req.setRequestHeader(’Content-type’,<br /> ’application/x-www-form-urlencoded;charset=UTF-8;’);<br /> req.send(’hello=world&XMLHttpRequest=test’);<br /> if(req.status == 200)<br /> alert(req.responseText);<br />

2.1.3 XMLHttpRequest::setRequestHeader()

There are many different cases in which setting a header on a request might be useful. The most common use of setRequestHeader() is to set the Content-type, because most Web applications already know how to deal with certain types, such as URLencoded. The setRequestHeader method signature takes two parameters: the header to set and its value:

1

setRequestHeader(header,value)

setRequestHeader(header,value)<br />

Because requests sent using XMLHttpRequest send the
same standard headers, including cookie headers and HTTP authentication
headers, as a normal browser request, the header name will usually be
the name of the HTTP header that you want to override. In addition to
overriding default headers, setRequestHeader is useful for setting custom, application-specific headers. Custom headers are generally prefixed with X- to distinguish them from standard ones. The following example makes a synchronous GET request adding a header called X-foo to test.php. If test.php contains <?php var_dump($_SERVER); ?>, you will see the submitted header in the alert:

1

var req = new XMLHttpRequest();

2

req.open(’GET’, ’test.php’, false);

3

req.setRequestHeader(’X-foo’,’bar’);

4

req.send(null);

5

6

if(req.status == 200)

7

alert(req.responseText);

var req = new XMLHttpRequest();<br /> req.open(’GET’, ’test.php’, false);<br /> req.setRequestHeader(’X-foo’,’bar’);<br /> req.send(null);</p> <p>if(req.status == 200)<br /> alert(req.responseText);<br />

2.1.4 XMLHttpRequest::getResponseHeader() and getAllResponseHeaders()

The getResponseHeader method allows you to get a single header from the response; this is especially useful when all you need is a header like Content-type; note that the specified header is case-insensitive. The method signature is as follows:

1

getResponseHeader(header)

getResponseHeader(header)<br />

getAllResponseHeaders returns all the headers from the
response in a single string; this is useful for debugging or searching
for a value. The following example makes a synchronous GET request to test.html. When the client receives a response, the Content-type is alerted and all the headers are alerted:

1

var req = new XMLHttpRequest();

2

req.open(’GET’, ’test.html’, false);

3

req.send(null);

4

5

if(req.status == 200) {

6

alert(req.getResponseHeader(’Content-type’));

7

alert(req.getAllResponseHeaders());

8

}

var req = new XMLHttpRequest();<br /> req.open(’GET’, ’test.html’, false);<br /> req.send(null);</p> <p>if(req.status == 200) {<br /> alert(req.getResponseHeader(’Content-type’));<br /> alert(req.getAllResponseHeaders());<br /> }<br />

2.1.5 Other XMLHttpRequest Methods

All browsers implement an abort() method, which is
used to cancel an in-progress asynchronous request. (An example of this
is shown in the “Sending Asynchronous Requests” section in this
chapter.) Mozilla-based browsers also offer some extra methods on top
of the basic API; for instance, addEventListener() and removeEventListener() provide a way to catch status events without using the on* properties. There is also an overrideMimeType() method that makes it possible to force the Content-type to text/xml
so that it will be parsed into a DOM document even if the server
doesn’t report it as such. The Mozilla-specific methods can be useful
in certain circumstances, but in most cases, you should stay away from
them because not all browsers support them.

2.1.6 XMLHttpRequest Properties

XMLHttpRequest provides a number of properties that
provide information or results about the request. Most of the
properties are self-explanatory; you simply read the value and act on
it. The on* properties are event handlers that are used by assigning a function to them. A list of all the properties follows:

  • status. The HTTP status code of the request response.
  • statusText. The HTTP status code that goes with the code.
  • readyState. The state of the request. (See Table 2-1 in the next section of this chapter for values.)
  • responseText. Unparsed text of the response.
  • responseXML. Response parsed into a DOM Document object; happens only if Content-type is text/xml.
  • onreadystatechange. Event handler that is called when readyState changes.
  • onerror. Mozilla-only event handler that is called when an error happens during a request.
  • onprogress. Mozilla-only event handler that is called at an interval as content is loaded.
  • onload. Mozilla-only event handler that is called when the document is finished loading.

NOTE

Mozilla resets event handlers, such as onreadystatechange, after a request is completed, so you need to reset them if you are making multiple calls with the same object.

2.1.7 readyState Reference

Table 2-1 shows the possible values for the readyState variable. It will return a number representing the current state of the object. Each request will progress through the list of readyStates.

Table 2-1 readyState Levels

readyState Status Code

Status of the XMLHttpRequest Object

(0) UNINITIALIZED

The object has been created but not initialized. (The open method has not been called.)

(1) LOADING

The object has been created, but the send method has not been called.

(2) LOADED

The send method has been called, but the status and headers are not yet available.

(3) INTERACTIVE

Some data has been received. Calling the responseBody and responseText
properties at this state to obtain partial results will return an
error, because status and response headers are not fully available.

(4) COMPLETED

All the data has been received, and the complete data is available in the responseBody and responseText properties.

The readyState variable and the onreadystatechange event handler are linked in such a way that each time the readyState variable is changed, the onreadystatechange event handler is called.

2.2 Cross-Browser XMLHttpRequest

One of the attributes that have made XMLHttpRequest
such a popular transport for Ajax requests is that it is easy to use in
a way that is compatible across multiple browsers. The big two
browsers, IE and Firefox, provide the same basic API. This consistency
makes for a similar development experience. Opera and Safari also
support the same basic API, but only in their more recent versions.

When you are writing cross-browser, the first problem you need to overcome is that XMLHttpRequest
is an ActiveX object in IE, and it’s a normal JavaScript object in
Mozilla and the other browsers. There are a number of approaches to
overcoming this problem, including optional JScript code for IE, but I
find that the simplest solution is just to use exceptions. Listing 2-1
shows an example that tries every version of the XMLHTTP
ActiveX object, if needed. This helps make our implementation as robust
as possible. The function also throws an exception if it’s not possible
to create an XMLHttpRequest object. This gives us a way to give error messages or to fall back to IFrame requests, if needed.

Listing 2-1 Cross-Browser XMLHttpRequest Creation

1

// function to create an XMLHttpClient in a cross-browser manner

2

function initXMLHttpClient() {

3

var xmlhttp;

4

try {

5

// Mozilla / Safari / IE7

6

xmlhttp = new XMLHttpRequest();

7

} catch (e) {

8

// IE

9

var XMLHTTP_IDS = new Array(’MSXML2.XMLHTTP.5.0’,

10

’MSXML2.XMLHTTP.4.0’,

11

’MSXML2.XMLHTTP.3.0’,

12

’MSXML2.XMLHTTP’,

13

’Microsoft.XMLHTTP’ );

14

var success = false;

15

for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {

16

try {

17

xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);

18

success = true;

19

} catch (e) {}

20

}

21

if (!success) {

22

throw new Error(’Unable to create XMLHttpRequest.’);

23

}

24

}

25

return xmlhttp;

26

}

// function to create an XMLHttpClient in a cross-browser manner<br /> function initXMLHttpClient() {<br /> var xmlhttp;<br /> try {<br /> // Mozilla / Safari / IE7<br /> xmlhttp = new XMLHttpRequest();<br /> } catch (e) {<br /> // IE<br /> var XMLHTTP_IDS = new Array(’MSXML2.XMLHTTP.5.0’,<br /> ’MSXML2.XMLHTTP.4.0’,<br /> ’MSXML2.XMLHTTP.3.0’,<br /> ’MSXML2.XMLHTTP’,<br /> ’Microsoft.XMLHTTP’ );<br /> var success = false;<br /> for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {<br /> try {<br /> xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);<br /> success = true;<br /> } catch (e) {}<br /> }<br /> if (!success) {<br /> throw new Error(’Unable to create XMLHttpRequest.’);<br /> }<br /> }<br /> return xmlhttp;<br /> }<br />

The overall pattern of this code is simple: Create an XMLHttpRequest
instance in the most optimal way possible, as shown in line 6. This
creation should always succeed on Mozilla-based browsers, such as
Firefox, on Opera, and on the upcoming IE 7.

If XMLHttpRequest doesn’t exist, catch the exception
that is thrown, as shown in line 7. Getting an exception means you’re
on IE or an old browser. To test for IE, attempt to create an ActiveX
version of XMLHttpRequest, which is accomplished by the following:

  1. Looping over all possible ActiveX identifiers. This action will
    create an ActiveX instance for each identifier until the creation
    succeeds, setting the success flag to true, as shown in lines 9–20.
  2. If creation is successful, returning an XMLHttpRequest instance, as shown in line 25. Otherwise, throwing a JavaScript exception, as shown in line 22.

This approach allows for minimal overhead if the browser supports a native XMLHttpRequest object while fully supporting IE. It also gives us an error if XMLHttpRequest
isn’t supported at all. This error could be displayed to the user at
this point, or you could insert another communication approach, such as
hidden IFrames.

2.3 Sending Asynchronous Requests

Synchronous requests are easier to use than asynchronous requests
because they return data directly and remove the hassle of creating
callback functions. However, they aren’t the standard use case for XMLHttpRequest
because the entire browser is locked while the request is happening.
There are some circumstances in which blocking is useful (mainly when a
decision needs to be made before the current function ends), but in
most cases, you’ll want these requests to happen in the background. An
asynchronous request allows the browser to continue running JavaScript
code and users to continue interacting with the page while the new data
is loaded. With the proper user interface, asynchronous communication
allows an Ajax application to be useful even when the user’s connection
to the site is slow.

To make an asynchronous call, we need to accomplish two tasks: set the asynchronous flag on open to true, and add a readyStateChanged
event handler. This event handler will wait for a ready state of 4,
which means the response is loaded. It will then check the status
property. If the status is 200, we can use responseText; if it’s another value, we have an error, so we’ll need to create an alert dialog to show it. An asynchronous call to test.php is shown in Listing 2-2. The initXMLHttpClient function from an earlier chapter section, “Cross-Browser XMLHttpRequest,” is used to create our XMLHttpRequest object.

Listing 2-2 Making an Asynchronous Request

1

var req = initXMLHttpClient();

2

req.onreadystatechange = function() {

3

if (req.readyState == 4) {

4

if (req.status == 200) {

5

alert(req.responseText);

6

} else {

7

alert(’Loading Error: [’+req.status+’] ’

8

+req.statusText);

9

}

10

}

11

}

12

req.open(’GET’,’test.php’,true);

13

req.send(null);

var req = initXMLHttpClient();<br /> req.onreadystatechange = function() {<br /> if (req.readyState == 4) {<br /> if (req.status == 200) {<br /> alert(req.responseText);<br /> } else {<br /> alert(’Loading Error: [’+req.status+’] ’<br /> +req.statusText);<br /> }<br /> }<br /> }<br /> req.open(’GET’,’test.php’,true);<br /> req.send(null);<br />

Although this code gets the job done, it’s not a great long-term solution because we will have to write a new onreadystatechange method for each call. The solution to this is to create our own HttpClient class that wraps XMLHttpRequest.
Such a class gives us an easy-to-use API and a property to use for the
callback that has to deal only with successful requests. Just adding
some helper methods would be a simpler solution, but that’s not a
possibility because IE doesn’t allow you to add methods to an ActiveX
object.

A sample XMLHttpRequest wrapper class is shown in Listing 2-3. The main features of the HttpClient class are a callback property that is called when a successful asynchronous request is complete and a makeRequest method that combines the open and send functions. It also provides event properties that are called when a request is made (onSend), when it ends (onload), and when an errors occurs (onError). A default onSend and onLoad implementation is provided, which creates a basic loading message while requests are being made.

Listing 2-3 HttpClient XMLHttpRequest Wrapper

1

function HttpClient() { }

2

HttpClient.prototype = {

3

// type GET,POST passed to open

4

requestType:’GET’,

5

// when set to true, async calls are made

6

isAsync:false,

7

8

// where an XMLHttpRequest instance is stored

9

xmlhttp:false,

10

11

// what is called when a successful async call is made

12

callback:false,

13

14

// what is called when send is called on XMLHttpRequest

15

// set your own function to onSend to have a custom loading

16

// effect

17

onSend:function() {

18

document.getElementById(’HttpClientStatus’).style.display =

19

’block’;

20

},

21

22

// what is called when readyState 4 is reached, this is

23

// called before your callback

24

onload:function() {

25

document.getElementById(’HttpClientStatus’).style.display =

26

’none’;

27

},

28

29

// what is called when an http error happens

30

onError:function(error) {

31

alert(error);

32

},

33

34

// method to initialize an xmlhttpclient

35

init:function() {

36

try {

37

// Mozilla / Safari

38

this.xmlhttp = new XMLHttpRequest();

39

} catch (e) {

40

// IE

41

var XMLHTTP_IDS = new Array(-’MSXML2.XMLHTTP.5.0’,

42

-’MSXML2.XMLHTTP.4.0’,

43

’MSXML2.XMLHTTP.3.0’,

44

’MSXML2.XMLHTTP’,

45

-’Microsoft.XMLHTTP’);

46

var success = false;

47

for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {

48

try {

49

this.xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);

50

success = true;

51

} catch (e) {}

52

-}

53

if (!success) {

54

this.onError(’Unable to create XMLHttpRequest.’);

55

}

56

}

57

},

58

59

// method to make a page request

60

// @param string url The page to make the request to

61

// @param string payload What you’re sending if this is a POST

62

// request

63

makeRequest: function(url,payload) {

64

if (!this.xmlhttp) {

65

this.init();

66

}

67

this.xmlhttp.open(this.requestType,url,this.isAsync);

68

69

// set onreadystatechange here since it will be reset after a

70

//completed call in Mozilla

71

var self = this;

72

this.xmlhttp.onreadystatechange = function() {

73

self._readyStateChangeCallback(); }

74

75

this.xmlhttp.send(payload);

76

77

if (!this.isAsync) {

78

return this.xmlhttp.responseText;

79

}

80

},

81

82

// internal method used to handle ready state changes

83

_readyStateChangeCallback:function() {

84

switch(this.xmlhttp.readyState) {

85

case 2:

86

this.onSend();

87

break;

88

case 4:

89

this.onload();

90

if (this.xmlhttp.status == 200) {

91

this.callback(this.xmlhttp.responseText);

92

} else {

93

this.onError(’HTTP Error Making Request: ’+

94

-’[’+this.xmlhttp.status+’]’+

95

-’+this.xmlhttp.statusText));

96

}

97

break;

98

}

99

}

100

}

function HttpClient() { }<br /> HttpClient.prototype = {<br /> // type GET,POST passed to open<br /> requestType:’GET’,<br /> // when set to true, async calls are made<br /> isAsync:false,</p> <p> // where an XMLHttpRequest instance is stored<br /> xmlhttp:false,</p> <p> // what is called when a successful async call is made<br /> callback:false,</p> <p> // what is called when send is called on XMLHttpRequest<br /> // set your own function to onSend to have a custom loading<br /> // effect<br /> onSend:function() {<br /> document.getElementById(’HttpClientStatus’).style.display =<br /> ’block’;<br /> },</p> <p> // what is called when readyState 4 is reached, this is<br /> // called before your callback<br /> onload:function() {<br /> document.getElementById(’HttpClientStatus’).style.display =<br /> ’none’;<br /> },</p> <p> // what is called when an http error happens<br /> onError:function(error) {<br /> alert(error);<br /> },</p> <p> // method to initialize an xmlhttpclient<br /> init:function() {<br /> try {<br /> // Mozilla / Safari<br /> this.xmlhttp = new XMLHttpRequest();<br /> } catch (e) {<br /> // IE<br /> var XMLHTTP_IDS = new Array(-’MSXML2.XMLHTTP.5.0’,<br /> -’MSXML2.XMLHTTP.4.0’,<br /> ’MSXML2.XMLHTTP.3.0’,<br /> ’MSXML2.XMLHTTP’,<br /> -’Microsoft.XMLHTTP’);<br /> var success = false;<br /> -for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {<br /> try {<br /> -this.xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);<br /> success = true;<br /> } catch (e) {}<br /> -}<br /> -if (!success) {<br /> -this.onError(’Unable to create XMLHttpRequest.’);<br /> }<br /> }<br /> },</p> <p> // method to make a page request<br /> // @param string url The page to make the request to<br /> // @param string payload What you’re sending if this is a POST<br /> // request<br /> makeRequest: function(url,payload) {<br /> if (!this.xmlhttp) {<br /> this.init();<br /> }<br /> this.xmlhttp.open(this.requestType,url,this.isAsync);</p> <p> -// set onreadystatechange here since it will be reset after a<br /> //completed call in Mozilla<br /> var self = this;<br /> this.xmlhttp.onreadystatechange = function() {<br /> self._readyStateChangeCallback(); }</p> <p> this.xmlhttp.send(payload);</p> <p> if (!this.isAsync) {<br /> return this.xmlhttp.responseText;<br /> }<br /> },</p> <p>// internal method used to handle ready state changes<br /> _readyStateChangeCallback:function() {<br /> switch(this.xmlhttp.readyState) {<br /> case 2:<br /> this.onSend();<br /> break;<br /> case 4:<br /> this.onload();<br /> if (this.xmlhttp.status == 200) {<br /> this.callback(this.xmlhttp.responseText);<br /> } else {<br /> -this.onError(’HTTP Error Making Request: ’+<br /> -’[’+this.xmlhttp.status+’]’+<br /> -’+this.xmlhttp.statusText));<br /> }<br /> break;<br /> }<br /> }<br /> }<br />

The HttpClient class contains comments explaining its
basic functionality, but you will want to look at a couple of areas in
detail. The first areas are the properties you’ll want to set while
interacting with the class; these include the following:

  • requestType (line 4). Used to set the HTTP request type, GET is used to request content that doesn’t perform an action whereas POST is used for requests that do.
  • isAsync (line 6). A
    Boolean value used to set the request method. The default is false,
    which makes an synchronous request. If you’re making an asynchronous
    request, isAsync is set to true. When making an asynchronous request, you also need to set the callback property.
  • callback (line 12). This property takes a function that takes a single parameter result and is called when a request is successfully completed.

Lines 16–31 contain simple functions for handling some basic user
feedback. When a request is sent to the server, a DOM element with the
ID of HttpClientStatus
is shown (lines 16–19). When it completes, it is hidden again (lines
23–26). The class also defines a function to call when an error happens
(lines 29–31); it creates an alert box with the error message. Common
errors include receiving a 404 page not found HTTP error message or not being able to create an XMLHttpRequest
object. The implementation of these three functions is simple, and
you’ll likely want to override them with more sophisticated
application-specific versions.

Lines 33–56 contain the init method, which is identical to the initXMLHttpClient function we created in Listing 2-1, except for what it does with its error message. Now it sends it to the onError method. You won’t be dealing with this function directly because the makeRequest method will take care of it for you. The makeRequest
method (lines 62–79) is your main interaction with the class. It takes
two parameters: a URL to which to make the request and a payload that
is sent to the server if you’re making a POST request. The actual implementation is a more generic version of the code shown in Listing 2-2. The _readyStateChangeCallback (lines 82–99) method is set as the readyState handler by makeRequest. It handles calling onSend when the initial request is sent and then calling onload when the request completes. It also checks for a 200 HTTP status code and calls onError if some other status is returned.

Listing 2-4 uses the HttpClient class and shows its
basic usage. A wrapper class like this helps cut down the amount of
code you need to write per request while giving a single place to make
future changes.

Listing 2-4 Using the HttpClient XMLHttpRequest Wrapper

1

<html>

2

<head>

3

<title>Simple XMLHttpRequest Wrapper Test Page</title>

4

5

<script type=“text/javascript” src=“HttpClient.js”></script>

6

<body>

7

<script type=“text/javascript”>

8

9

var client = new HttpClient();

10

client.isAsync = true;

11

12

function test() {

13

client.callback = function(result) {

14

document.getElementById(’target’).innerHTML = result;

15

}

16

client.makeRequest(’.’,null);

17

}

18

</script>

19

20

<div id=“HttpClientStatus” style=“display:none”>Loading …</div>

21

<a href=’javascript:test()’>Make an Async Test call</a>

22

<div id=“target”></div>

23

</body>

24

</html>

<html><br /> <head><br /> <title>Simple XMLHttpRequest Wrapper Test Page</title></p> <p><mce:script type=”text/javascript” src=”HttpClient.js” mce_src=”HttpClient.js”></mce:script><br /> <body><br /> <mce:script type=”text/javascript”><!– </p> <p>var client = new HttpClient();<br /> client.isAsync = true;</p> <p>function test() {<br /> client.callback = function(result) {<br /> document.getElementById(’target’).innerHTML = result;<br /> }<br /> client.makeRequest(’.’,null);<br /> }<br /> // –></mce:script></p> <p><div id=”HttpClientStatus” style=”display:none” mce_style=”display:none”>Loading …</div><br /> <a href=”’javascript:test()’” mce_href=”’javascript:test()’”>Make an Async Test call</a><br /> <div id=”target”></div><br /> </body><br /> </html><br />

Using the HttpClient XMLHttpRequest wrapper is a
simple task. You start by including it in the header of your HTML page
(line 5), and then you can proceed to use it. You do this by creating
an instance of the class (line 9), configuring its basic properties (in
this case, setting isAsync to true (line 10)), and then setting up some code to call makeRequest.
In most cases, this code will be contained in a function so that it can
be tied to a user-driven event, such as clicking a link. The call is
made by the test function (lines 12–17); the test function first sets up a callback to run when the request is complete (lines 13–15), and then it calls makeRequest (line 16), which starts the Ajax call.

2.4 Ajax Without XMLHttpRequest

There are a number of cases in which you might not have XMLHttpRequest
support. The most common would be in the case of an older browser. This
is the hardest to work around, not because there is no Ajax fallback,
but because all the other DOM manipulation that you do within the
application won’t work. Another problem case is when your browser
supports everything that is needed except for XMLHttpRequest. This problem could occur when IE is in a mode where it can’t use ActiveXObjects
or when you are using a pre-7.6 version of Opera. In some cases,
especially intranet applications, it’s easy to just require an upgrade,
but if you want to use Ajax on a public site, you’ll want to think
about using some sort of fallback mechanism. The best candidate for a
fallback is to use hidden IFrames. Another option is to
use cookies, but they can send only a limited amount of data per
request, so it is hard to drop in cookie-based approaches as a
replacement for code that has been written with XMLHttpRequest in mind. Only XMLHttpRequest supports synchronous calls, so if they are necessary for your application, then using it as a fallback will not be possible.

If you’re using a fully wrapped XMLHttpRequest and
you don’t use synchronous calls, providing transparent fallback to your
program should be possible. You need only to replace the final throwing
of an exception in the example init method with the instantiation of your IFrame HTTP client. The main item to remember about using another approach instead of XMLHttpRequest is that it’s not going to gain you huge leaps in compatibility. The major browsers already support XMLHttpRequest.
This support makes browsers with JavaScript turned off, not those
running an unsupported browser, the biggest group that can’t use your
Ajax application. The advantages and disadvantages of the Ajax
communication techniques are shown in Table 2-2.

Table 2-2 Advantages and Disadvantages of Ajax Techniques

Technique

Advantages

Disadvantages

XMLHttpRequest

Can make requests to pages not set up for Ajax

Can set/get all HTTP headers

Can make HTTP requests using any type (GET, POST, PROPFIND, and so on)

Supports full control over POST requests, allowing for any type of data encoding

Requests ActiveX to be enabled in IE 5 and 6

Is only available in newer versions of Opera and Safari

Has small implementation differences between browsers

IFrame

Can make POST and GET HTTP requests

Supportes all modern browsers

Supports asynchronous file uploads

Prohibits synchronous requests

Server pages must be designed to work with IFrame requests

Has implementation differences between browsers

Can leave extra entries in browser history (depends on browser and implementation)

All request data is URL-encoded, increasing request size


Cookies

Supports the largest number of browsers

Few implementation differences between browsers

Prohibits no synchronous requests

Doesn’t work with large requests/results

Requires server pages to be designed to work with cookie requests

Requires polling on the client

Can make only GET HTTP requests

Posted by: Expertz Web

Advertisements

0 Responses to “Getting Started: Ajax”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




RSS web design Company in India

  • An error has occurred; the feed is probably down. Try again later.

%d bloggers like this: