What is the XMLHttpRequest object in Ajax



Ajax combines JavaScript, HTML, DHTML, DOM and XML to make programming interactive web pages easier.

Without Ajax, user input on websites is usually sent to the server as a request, the server waits for a response and the HTML page is rebuilt. This leads to less fluid work than with desktop applications.

When using Ajax, communication does not take place directly from the HTML form to the server, but JavaScript code is switched in between and communication takes place via an XMLHttpRequest object, usually asynchronously and via XML data exchange. After sending requests, you can continue working in the client. When the response from the server arrives, the XMLHttpRequest object calls a client-side callback method, which can then update parts of the website, for example.

The XMLHttpRequest object is available in most modern web browser versions (from versions: Microsoft Internet Explorer 5.0, Mozilla Firefox 1.0, Netscape 7.1, Apple Safari 1.2, Opera Mobile Browser 8.0).



content

  1. Debugging and DOM Inspector
  2. The XMLHttpRequest object
  3. First minimal Ajax programming example (without XML)
  4. Simple server-side service for the first Ajax example
  5. Example Ajax client with return via XML
  6. Simple server-side service for the second Ajax example (with XML)
  7. Ajax example for autocomplete
  8. Simple server-side service for the Ajax example with autocompletion
  9. Links to further information


Debugging and DOM Inspector

If you have problems executing the JavaScripts, you should turn on debugging tools. The DOM Inspector is helpful to understand the DOM model better.

Mozilla Firefox

In order to get JavaScript error messages displayed in Mozilla Firefox, enter the URL address: ''. Alternatively, you can also choose: 'Extras' | 'JavaScript Console'.

To debug JavaScript in Firefox, install the Venkman JavaScript Debugger from: http://www.mozilla.org/projects/venkman/.

In order to use the Firefox DOM Inspector, you do not need to install Firefox in the 'Standard' installation, but rather 'User-defined' and activate the 'Developer Tools' under 'Select Components'. You can then call up the DOM Inspector via 'Extras' | 'DOM Inspector'.

Microsoft Internet Explorer

In Microsoft Internet Explorer, go to 'Tools' | 'Internet options ...' | 'Extended' | 'Browsing':
Deactivate 'Deactivate script debugging' and
Activate 'Show script errors'.

If you not only want JavaScript errors to be displayed, but also want to step through the JavaScript code, you should download and install the Microsoft Script Debugger for Windowsscd10en.exe in addition to the above setting.



The XMLHttpRequest object

The JavaScript object "XMLHttpRequest" forms the core of Ajax. A tabular overview of the most important methods and attributes follows. The functionality is illustrated in the examples in the next chapters.

Further explanations can be found at http://xulplanet.com/references/objref/XMLHttpRequest.html and http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/objects/ obj_xmlhttprequest.asp.

The main methods of XMLHttpRequest
open (httpReqMeth, url, async)

open (httpReqMeth, url, async, usr, pwd)
Specifies the Ajax communication:
httpReqMeth = HTTP request method ('GET', 'POST', 'PUT')
url = URL of the service
async = true for asynchronous communication (client does not wait for an answer, callback function is called instead)
usr = Username (optional)
pwd = Password (optional)
send (postReq)
Sends the request to the server:
postReq = null for 'GET' requests,
or key-value pairs separated by '&' for 'POST' requests
(e.g. "Key1 = Value1 & Key2 = Value2 & Key3 = Value3")
abort ()Cancels a currently running request
setRequestHeader (key, value)Adds a key-value pair to the HTTP header
(e.g .: setRequestHeader ('Content-Type', 'application / x-www-form-urlencoded');)
getResponseHeader (key)HTTP header entry for the given key
getAllResponseHeaders ()All HTTP header entries
The most important attributes of XMLHttpRequest
onreadystatechangeContains the event handler callback method which is called when the status of the XMLHttpRequest object changes, e.g. when a response from the server arrives
readyStateThe status of the XMLHttpRequest object is transmitted to the event handler callback method:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
statusThe HTTP status transmitted by the server, e.g .:
200 = OK
404 = Not Found
statusTextthe text that matches the HTTP status
responseTextThe server's response as a text string
responseXMLThe server's response in XML format as an XMLDocument, which is handled using DOM methods


First minimal Ajax programming example (without XML)

  1. The following example does not serve any useful purpose. It only shows the basic communication flow.

    Generate the following HTML file '':

    onload = "startAjax ()">

    My first Ajax test

  2. < / noscript>

    • Explanations:
    • The function '' defined by JavaScript is inserted in the '' HTML tag and is called by the web browser at the beginning of the website.
      A '' object is created in the '' function. Unfortunately, this must be done depending on the web browser:
    • In Microsoft Internet Explorer it is called ``, in other web browsers ''.
    • In addition, Ajax communication is triggered in the '' function via '' and ''. A service would normally be entered as the URL, which returns a meaningful response based on the parameters passed. For the sake of simplicity, no parameters are passed here and only a short website is requested.
    • The function '' defined by JavaScript is not called directly in the HTML or JavaScript code. It is only entered as a callback function in the '' method ''.
    • If the '' object can successfully receive a response to the transferred URL, it calls the callback function '', which can evaluate the result. In this simple example, only the answer is shown. The '' 4 means that the '' object has received the response in full. The HTTP server reports the usual HTTP codes via the '': 200 means 'OK', so no error.
  3. If you try one of the two suggested as '', your IP address will be displayed. If you enter a URL to a short HTML page, you will receive its source code.

    Microsoft Internet Explorer:
    If you are using Microsoft Internet Explorer 6, you can execute this HTML file directly. If you get the message "Please turn on JavaScript!" you have to get
    a) under 'Extras' | 'Internet options ...' | 'Security' | 'Customize level ...' Allow 'ActiveX' and

    b) if necessary, click on the yellow bar above the website display and select 'Allow blocked content ...'.

  4. Enter various URLs for short text files or HTML pages in the HTML source text under '', e.g .: http://checkip.dyndns.org.

    Other web browsers (e.g. Mozilla Firefox 1.5):
    Unfortunately, you cannot run the example with most other web browsers as their security settings expect the HTML file to be loaded from the same web server domain as the service.
    (E.g. with Firefox 1.5 you get the error message:
    "Permission to call the XMLHttpRequest.open method was denied".)



A service will therefore be installed on a web server in the next chapter.

  1. Simple server-side service for the first Ajax example
  2. In the first example only the HTML code for the web browser was generated. Existing services or HTML pages on the Internet were used. The services are decoupled from the client and can be created in any programming language, e.g. Perl, PHP, ASP.NET, JSP or Java. The following shows a trivial service programmed in JSP (Java Server Pages) that only returns the IP address of the caller (such a service can be useful if PCs are connected to the Internet via a NAT router).
  3. Install a current Java SE JDK as described under java-install.htm. Install one that matches your Java versionTomcat
  4. -Version as described under jsp-install.htm. Start Tomcat and check the installation by going to http: // localhost: 8080 in the web browser.

    <%= request.getRemoteHost() %>
  5. Create the subdirectory `` in your Tomcat '' directory (e.g. D: \ Tools \ Tomcat \ webapps \ ROOT). Create the following JSP file in the '' subdirectory:
  6. '' actually doesn't return an HTML page. Even so, most web browsers can display the result. Check this (with Tomcat running) by calling http: // localhost: 8080 / ajax / checkiptxt.jsp. You can see your IP address in the web browser (this is '' for the local Tomcat).
  7. Create the HTML file described in the first Ajax example above in your Tomcat '' subdirectory. In '' change the entry to '' to ''.
  8. Unlike above, this time '' is not loaded into the web browser as a file via the file system, but obtained as an HTML file via HTTP from the Tomcat web server: In the web browser, enter the URL http: // localhost: 8080 / ajax / AjaxTest1. html. The example now works not only in Microsoft Internet Explorer, but also in.
  9. all Ajax-enabled web browsers


If you have an account on a JSP server accessible on the Internet, you can also install '' and '' there.

  1. Example Ajax client with return via XML
  2. In the first Ajax example above, the return text was determined using ''. In the following example, several results are returned in an XML structure and determined using ''.
  3. Install Java and Tomcat as described above.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>AJAX</title> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> <script language="JavaScript" type="text/javascript"> Create the subdirectory '' in your Tomcat '' directory. Create the following HTML file in the '' subdirectory:var url0 = "ajaxtest.jsp"; var req;function myAjaxInit () { try {if (window.XMLHttpRequest) {req = new XMLHttpRequest (); } else if (window.ActiveXObject) {req = new ActiveXObject ("Microsoft.XMLHTTP"); } else {alert ("Unfortunately, your web browser does not support Ajax!"); } if (req.overrideMimeType) {req.overrideMimeType ('text / xml'); }} catch (e) {alert ("Error:" + e); }}function myAjaxCall () { if (req) {var numberEingabe = document.getElementById ("numberEingabe"); var textEingabe = document.getElementById ("textEingabe");var url = url0 + "? number =" + escape (numberInput.value) + "& text =" + escape (textInput.value); req.open ("GET", url, true); req.onreadystatechange = myCallbackFct; req.send (null); }}function myCallbackFct () { if (4 == req.readyState) {if (200! = req.status) {alert ("Error" + req.status + ":" + req.statusText); } else {result = req.responseXML.documentElement; var numberOutput = result.getElementsByTagName ('number') [0] .firstChild.data; var text output = result.getElementsByTagName ('text') [0] .firstChild.data; var ipAusgabe = result.getElementsByTagName ('ip') [0] .firstChild.data; document.getElementById ("number output").value = number output; document.getElementById ("textAusgabe").value = text output; document.getElementById ("ipAusgabe").innerHTML = ipoutput; }}}

    My second Ajax test

    Enter number: onKeyUp = "myAjaxCall ();"> square Enter text: onKeyUp = "myAjaxCall ();"
  4. > Sorted

    • IP address: <
    • span id = "ip output"
    • >
      Explanations:
      The function defined by JavaScript '' is inserted in the '' HTML tag and is called by the web browser at the beginning of the website. A '' object is created in the '' function, as already known from the first Ajax example above.
      The JavaScript expression '' in the HTML form triggers Ajax communication after each character entered via ''. The number and text entered are transferred as parameters in the URL to the Ajax service.
    • In the callback function '' called asynchronously by Ajax, the result values ​​are received as an XML structure via ''.


DOM is used for two different tasks:

  1. a) to extract the desired result from the returned XML structure (with '') and
  2. b) to insert the results into the HTML website (with '' or '').

    <? You could also add new nodes with '' in the HTML web page.Before you can try out '', you must create the service described in the next chapter. Simple server-side service for the second Ajax example (with XML)A suitable server service should also be programmed in JSP (Java Server Pages) for the Ajax XML example above. Install Java and Tomcat as described above and create the following JSP file '' in the Tomcat '' subdirectory that has already been created: <zahl><%= zahl %></zahl><text><%= text %></text><ip><%= request.getRemoteHost() %></ip> </MeinErgebnis>
  3. xml

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <MeinErgebnis> <zahl>144</zahl> <text>aaejttxx</text> <ip>127.0.0.1</ip> </MeinErgebnis>
  4. version = "1.0" encoding = "UTF-8" standalone = "yes"?> <% response.setContentType ("text / xml"); response.setHeader ("Cache-Control", "no-cache");
  5. String number = request.getParameter ("number");
  6. String text = request.getParameter ("text");


if (null == number || 0> = number.trim (). length ()) {number = "-"; } else {try {long i = Long.parseLong (number); number = "" + i * i; } catch (Exception ex) {/ * ok * /}} if (null == text || 0> = text.trim (). length ()) {text = "-"; } else {char [] c = text.toCharArray (); java.util.Arrays.sort (c); text = new String (c); }%>

  1. '' returns an XML file. Check this (with Tomcat running) by calling http: // localhost: 8080 / ajax / ajaxtest.jsp and http: // localhost: 8080 / ajax / ajaxtest.jsp? Number = 12 & text = ajaxtext. Depending on your web browser, you will get something like the following:
  2. The service should be used by the Ajax XML example above. Do not load '' as a file into the web browser via the file system, but rather as an HTML file via HTTP via the Tomcat web server by entering the URL http: // localhost: 8080 / ajax / AjaxTest2.html in the web browser.

    Enter numbers for '' and letters for ''. As you type, the square is calculated from the number and the letters are sorted alphabetically (please do not enter umlauts or special characters). Of course, you can also reinstall '' and '' on the Internet. Proceed as described above. Copy both files and go to the appropriate URL.Ajax example for autocomplete Install Java and Tomcat as described above. Create the subdirectory '' in your Tomcat '' directory. Create the following HTML file in the '' subdirectory: AJAX test: input autocompletion

    My Ajax test with input autocompletion

  • Explanations:


  • The function defined by JavaScript '' is inserted in the '' HTML tag and is called by the web browser at the beginning of the website. A '' object is created in the '' function, as already known from the Ajax examples above.

    1. The JavaScript expression '' in the HTML form triggers Ajax communication after each character entered via ''. The characters entered are transferred as parameters in the URL to the Ajax service.

      In the callback function '' called asynchronously by Ajax, the result is received with ''. The returned text can contain several lines of text that are separated with '' and then individually added to the clickable links in the autocomplete box.The lines of the auto-completion box react to mouse movements and mouse clicks via the JavaScript functions '' and ''. The distinction '' is necessary because of the different JavaScript implementations in Microsoft Internet Explorer and in Mozilla / Firefox browsers.Before you can try out '', you must create the service described in the next chapter. Simple server-side service for the Ajax example with autocompletion } %>
    2. Complete the Ajax autocomplete example as follows. Create the following JSP file '' in the Tomcat subdirectory that has already been created:
    3. <%! static final string []

    4. myTextArray
    5. = {"aabbcc", "abc 1", "abc1", "abc2", "ajax1", "ajax2", "xyzax", "xyzäx", "xyzbx", "xyzzx"}; boolean sorted = false; %> <% response.setHeader ("Cache-Control", "no-cache"); String input =
    6. request.getParameter ("input")


    ; if (null! = input && 0



    out.println (selection.toString ());
    Replace the text strings of the '' array with more meaningful texts (or load suitable texts from a file or database).