Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | “Raw” Ajax Example Using the XMLHttpRequest Object

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - Ajax-Enabled Rich Internet Applications

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

“Raw” Ajax Example Using the XMLHttpRequest Object

In this section, we use the XMLHttpRequest object to create and manage asynchronous requests.

“Raw” Ajax Example Using the XMLHttpRequest  Object

 

In this section, we use the XMLHttpRequest object to create and manage asynchronous requests. The XMLHttpRequest object (which resides on the client) is the layer between the client and the server that manages asynchronous requests in Ajax applications. This object is supported on most browsers, though they may implement it differently—a common is-sue in JavaScript programming. To initiate an asynchronous request (shown in Fig. 15.5), you create an instance of the XMLHttpRequest object, then use its open method to set up the request and its send method to initiate the request. We summarize the XMLHttpRe-quest properties and methods in Figs. 15.6–15.7.

 

Figure 15.5 presents an Ajax application in which the user interacts with the page by moving the mouse over book-cover images. We use the onmouseover and onmouseout events (discussed in Chapter 13) to trigger events when the user moves the mouse over and out of an image, respectively. The onmouseover event calls function getContent with the URL of the document containing the book’s description. The function makes this request asynchronously using an XMLHttpRequest object. When the XMLHttpRequest object receives the response, the book description is displayed below the book images. When the user moves the mouse out of the image, the onmouseout event calls function clearCon-tent to clear the display box. These tasks are accomplished without reloading the page on the client. You can test-drive this example at test.deitel.com/examples/iw3htp4/ajax/fig15_05/SwitchContent.html.

 

Asynchronous Requests

 

The function getContent (lines 19–35) sends the asynchronous request. Line 24 creates the XMLHttpRequest object, which manages the asynchronous request. We store the object in the global variable asyncRequest (declared at line 16) so that it can be accessed any-where in the script.

 

 

1    <?xml version = "1.0" encoding = "utf-8"?>

 

2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5    <!-- Fig. 15.5: SwitchContent.html -->

 

6    <!-- Asynchronously display content without reloading the page. -->

 

7    <html xmlns = "http://www.w3.org/1999/xhtml">

 

8    <head>

 

9          <style type="text/css">

 

10                .box { border: 1px solid black;

11                               padding: 10px }

 

12         </style>

 

13         <title>Switch Content Asynchronously</title>

 

14         <script type = "text/javascript" language = "JavaScript">

15                <!--

 

16                var asyncRequest; // variable to hold XMLHttpRequest object

17          

18                // set up and send the asynchronous request

 

19                function getContent( url )

20                {

 

21                      // attempt to create the XMLHttpRequest and make the request

22                      try

{

            asyncRequest = new XMLHttpRequest(); // create request object                 

24                               

25                               

26        // register event handler                 

27        asyncRequest.onreadystatechange = stateChange;               

28        asyncRequest.open( 'GET', url, true ); // prepare the request 

29        asyncRequest.send( null ); // send the request

30        } // end try

 

31                      catch ( exception )

32                      {

33                            alert( 'Request failed.' );

 

34                      } // end catch

 

35                } // end function getContent

36

37                // displays the response data on the page

 

38                function stateChange()

39                {

 

40                      if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )

{

            document.getElementById( 'contentArea' ).innerHTML =       

42                   

43        asyncRequest.responseText; // places text in contentArea    

44                      } // end if

 

45                } // end function stateChange

46          

47                // clear the content of the box

 

48                function clearContent()

49                {

 

50                      document.getElementById( 'contentArea' ).innerHTML = '';

 

51                } // end function clearContent

52                // -->

 

53         </script>

 

54   </head>

 

55   <body>

 

56         <h1>Mouse over a book for more information.</h1>

 

57         <img src =

 

58                "http://test.deitel.com/examples/iw3htp4/ajax/thumbs/cpphtp6.jpg"

 

59                onmouseover = 'getContent( "cpphtp6.html" )'

 

60                onmouseout = 'clearContent()'/>

 

61         <img src =

 

62                "http://test.deitel.com/examples/iw3htp4/ajax/thumbs/iw3htp4.jpg"

 

63                onmouseover = 'getContent( "iw3htp4.html" )'

 

64                onmouseout = 'clearContent()'/>

 

65         <img src =

 

66                "http://test.deitel.com/examples/iw3htp4/ajax/thumbs/jhtp7.jpg"

 

67                onmouseover = 'getContent( "jhtp7.html" )'

 

68                onmouseout = 'clearContent()'/>

 

69         <img src =

 

70                "http://test.deitel.com/examples/iw3htp4/ajax/thumbs/vbhtp3.jpg"

 

71                onmouseover = 'getContent( "vbhtp3.html" )'

 

72                onmouseout = 'clearContent()'/>

 

73         <img src =

 

74                 "http://test.deitel.com/examples/iw3htp4/ajax/thumbs/vcsharphtp2.jpg"

 

75                onmouseover = 'getContent( "vcsharphtp2.html" )'

 

76                onmouseout = 'clearContent()'/>

 

77         <img src =

 

78                "http://test.deitel.com/examples/iw3htp4/ajax/thumbs/chtp5.jpg"

 

79                onmouseover = 'getContent( "chtp5.html" )'

 

80                onmouseout = 'clearContent()'/>

 

81         <div class = "box" id = "contentArea">&nbsp;</div>

 

82   </body>

 

</html>



Fig. 15.5 | Asynchronously display content without reloading the page.

 

 

Line 28 calls the XMLHttpRequest open method to prepare an asynchronous GET request. In this example, the url parameter specifies the address of an HTML document containing the description of a particular book. When the third argument is true, the request is asynchronous. The URL is passed to function getContent in response to the onmouseover event for each image. Line 29 sends the asynchronous request to the server by calling XMLHttpRequest send method. The argument null indicates that this request is not submitting data in the body of the request.

 

Exception Handling

 

Lines 22–34 introduce exception handling. An exception is an indication of a problem that occurs during a program’s execution. The name “exception” implies that the problem occurs infrequently—if the “rule” is that a statement normally executes correctly, then the “excep-tion to the rule” is that a problem occurs. Exception handling enables you to create applica-tions that can resolve (or handle) exceptions—in some cases allowing a program to continue executing as if no problem had been encountered.

 

Lines 22–30 contain a try block, which encloses the code that might cause an excep-tion and the code that should not execute if an exception occurs (i.e., if an exception occurs in a statement of the try block, the remaining code in the try block is skipped). A try block consists of the keyword try followed by a block of code enclosed in curly braces ({}). If there is a problem sending the request—e.g., if a user tries to access the page using an older browser that does not support XMLHttpRequest—the try block terminates imme-diately and a catch block (also called a catch clause or exception handler) catches (i.e., receives) and handles an exception. The catch block (lines 31–34) begins with the key-word catch and is followed by a parameter in parentheses (called the exception parameter) and a block of code enclosed in curly braces. The exception parameter’s name (exception in this example) enables the catch block to interact with a caught exception object (for example, to obtain the name of the exception or an exception-specific error message via the exception object’s name and message properties). In this case, we simply display our own error message 'Request Failed' and terminate the getContent function. The request can fail because a user accesses the web page with an older browser or the content that is being requested is located on a different domain.

 

Callback Functions

The stateChange function (lines 38–45) is the callback function that is called when the client receives the response data. Line 27 registers function stateChange as the event handler for the XMLHttpRequest object’s onreadystatechange event. Whenever the request makes progress, the XMLHttpRequest calls the onreadystatechange event handler. This progress is monitored by the readyState property, which has a value from 0 to 4. The value 0 indicates that the request is not initialized and the value 4 indicates that the request is complete—all the values for this property are summarized in Fig. 15.6. If the request completes successfully (line 40), lines 42–43 use the XMLHttpRequest object’s responseText property to obtain the response data and place it in the div element named contentArea (defined at line 81). We use the DOM’s getElementById method to get this div element, and use the element’s innerHTML property to place the content in the div.

 

XMLHttpRequest Object Properties and Methods

Figures 15.6 and 15.7 summarize some of the XMLHttpRequest object’s properties and methods, respectively. The properties are crucial to interacting with asynchronous re-quests. The methods initialize, configure and send asynchronous requests.






Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.