My First AJAX - the simplest Asynchronuous JavaScript Server call man can imagine html

My First AJAX – the simplest Asynchronuous JavaScript Server call man can imagine

Inspired by Aino’s post AJAX and RIA, I wanted to get my first XMLHttpRequest object based AJAX example getting up and running. It is a standalone HTML page that can be deployed on any webserver (I ran it from inside JDeveloper). When the Submit button is pressed, the page itself is invoked and the returned value (the HTML for the page itself) is stored in the Text Field. You cannot get it any simpler than this. Of course, normally the Request would be a sensible one, to a WebService or a Servlet or even JSP that returns a useful value to the browser.

    <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"></meta>
    <title>Ajax Try Out</title><SCRIPT language="JavaScript">
    var req;
  function loadXMLDoc(url) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;"GET", url, true);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
  "GET", url, true);
  function processReqChange()  {
          document.forms['simpleform'].simplefield.value="response received";
         // only if req shows "complete"
        if (req.readyState = = 4) {
          // only if "OK"
          if (req.status = = 200) {
          response  = req.responseText;
          document.forms['simpleform'].simplefield.value=req.responseText; // do something with the response
          else {
              alert("There was a problem retrieving   the XML data:n" + req.statusText);

<H1>This is a very sober demonstration of Ajax</H1>
<P>When you click on the button, a request is sent to the WebServer. After some time, the response is received and used to update the text field. The actual response is created by a Servlet running in the WebServer.</P>
<form name="simpleform">
<input id="field1" value="defaultvalue" type="text" name="simplefield" onblur="loadXMLDoc(document.location.href) ;"/>
<input type="submit" onclick="loadXMLDoc(document.location.href);" value="Submit"/>
See for more examples:
<a href=””> Very Dynamic Web Interfaces</a>

One Response

  1. jojo July 13, 2005