Home > Articles > Programming > Java

This chapter is from the book

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);

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
       onSend:function() {
17         document.getElementById('HttpClientStatus').style.display =
18                               'block';
19     },
20
21     // what is called when readyState 4 is reached, this is
22     // called before your callback
23      onload:function() {
24          document.getElementById('HttpClientStatus').style.display =
25                              'none';
26      },
27
28     // what is called when an http error happens
29     onError:function(error) {
30         alert(error);
31     },
32
33     // method to initialize an xmlhttpclient
34     init:function() {
35       try {
36           // Mozilla / Safari
37            this.xmlhttp = new XMLHttpRequest();
38       } catch (e) {
39           // IE
40           var XMLHTTP_IDS = new Array('MSXML2.
                                         XMLHTTP.5.0',
41                                     'MSXML2.XMLHTTP.4.0',
42                                     'MSXML2.XMLHTTP.3.0',
43                                     'MSXML2.XMLHTTP',
44                                     'Microsoft.XMLHTTP');
45           var success = false;
46           for (var i=0;i < XMLHTTP_IDS.length &&
             !success; i++) {
47               try {
48                   this.xmlhttp = new ActiveXObject
                     (XMLHTTP_IDS[i]);
49                   success = true;
50               } catch (e) {}
51           }
52           if (!success) {
53               this.onError('Unable to create XMLHttpRequest.');
54           }
55        }
56     },
57
58     // method to make a page request
59     // @param string url  The page to make the request to
60     // @param string payload  What you're sending if this is a POST
61    //                        request
62    makeRequest: function(url,payload) {
63         if (!this.xmlhttp) {
64             this.init();
65         }
66         this.xmlhttp.open(this.requestType,url,this.isAsync);
67
68         // set onreadystatechange here since it will be reset after a
69        //completed call in Mozilla
70         var self = this;
71         this.xmlhttp.onreadystatechange = function() {
72        self._readyStateChangeCallback(); }
73
74         this.xmlhttp.send(payload);
75
76         if (!this.isAsync) {
77             return this.xmlhttp.responseText;
78         }
79    },
80
81     // internal method used to handle ready state changes
82    _readyStateChangeCallback:function() {
83         switch(this.xmlhttp.readyState) {
84              case 2:
85               this.onSend();
86               break;
87            case 4:
88               this.onload();
89               if (this.xmlhttp.status == 200) {
90                   this.callback(this.xmlhttp.responseText);
91               } else {
92                   this.onError('HTTP Error Making Request: '+
93                                       '['+this.xmlhttp.
                                         status+']'+
94                                       '+this.xmlhttp.
                                         statusText));
95               }
96               break;
97         }
98     }
99 }

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>

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020