Introduction


AJAX can be very confusing due to the mix of technologies involved. A set of examples with increasing complexity attempts to show the principles behind it. A more simplified example is in part (2), and the most basic one is in part (1).

From here, we want to add arguments to the Ajax request itself. These arguments are transpoted through the calling URL, and need to be processed on the server side. The goal is to create a selective response as a result of a users choice in a HTML form. Here, we finally will replace our server-side text file with a real (CGI) program.

Example Code


In updating our example, we add function arguments to set the data provider and the update target; and we improve the event handler's error detection.

<html><head>
<script language="javascript" type="text/javascript">
<!--
  // First create an Ajax request, depending on the browser.
  var ajaxRequest = null;

  // For Opera 8.0+, Firefox or Safari
  if (window.XMLHttpRequest) {
    ajaxRequest = new XMLHttpRequest();
  }
  // For older Internet Explorer Browsers
  else if (window.ActiveXObject) {
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }
  // Raise alert for problems
  else {
    alert("Error in page: could not create AJAX request.");
  }

  // The main Ajax function
  function ajaxCall(url, Id){
    if(ajaxRequest) {

      // (1) Hardcode the data provider
      ajaxRequest.open("GET", url, true);

      // (2) Hardcode the update target
      var ajaxTarget = document.getElementById(Id);

      // (3) create the event handler
      ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4) {
          if(ajaxRequest.status == 200) {
            ajaxTarget.innerHTML = ajaxRequest.responseText;
          }
          else {
            ajaxTarget.innerHTML = "Error: "+ajaxRequest.status
                                  +" = "+ajaxRequest.statusText;
          }
        }
      }

      // (4) call the send() command, using form data as params
      
      queryParams = setQueryStr();
      ajaxRequest.send(queryParams);
      
    }
  }

  // The function setQueryStr() going to cycle through
  // all form elements of the form with the hardcoded
  // name 'ajax-form', and builds the query string to
  // be added to our AJAX URL call (no leading ? char).
  
  function setQueryStr() {
    var form = document.forms['ajax-form'];
    var qstr = false;

    // add the first query param, a hidden field with the ip
    qstr = form.sysip.name + "=" + escape(form.sysip.value);

    // add the second query param, the selected radio box
    qstr = qstr + "&" + getType().name + "=" + escape(getType().value);

    return qstr;
  }

  // The function getType() returns the selected radio button,
  // using a hardcoded form and radio button group name.
  
  function getType() {
    var form = document.forms['ajax-form'];
    var type = false;

    for (var i=0; i < form.ptype.length; i++) {
      if (form.ptype[i].checked) {
        type = form.ptype[i];
      }
    }
    return type;
  }

  // The function setDescr() sets the field description
  // depending on the radio buttons choice.
  
  function setDescr() {
   var target = document.getElementById('query-type');
   target.innerHTML = getType().value;
  }

//-->
</script>
</head>
<body onLoad="setDescr();">

<h4>Ajax Test Example 3</h4>

<p>Our Ajax call will add parameters to the URL call, depending on the choice made below.
The server-side program will parse the arguments, and return the selected data type.</p>

<p><b>Ajax Request:</b></p>
<form name="ajax-form">
  <input type="hidden" name="sysip" value="127.0.0.1">
  <input type="radio" name="ptype" value="Load" checked="checked" 
   onChange="setDescr();" />System Load<br>
  <input type="radio" name="ptype" value="Memory"
   onChange="setDescr();" />System Memory
  <p>
  <input type="button" value="Get Data" onClick="ajaxCall('ajaxtest3.cgi', 'query-data');" />
  </p>
</form>

<p><b>Ajax Response:</b></p>
<table border="1" width="400px">
  <tr><th colspan="2">Server Performance Data</th></tr>
  <tr>
    <td class="odd" id="query-type" width="150px">&nbsp;</td>
    <td id="query-data"width="350px">&nbsp;</td>
  </tr>
</table>

</body></html>

On the server side, we create a CGI program called ajaxtest3.cgi CGI's are placed in a dedicated CGI directory, enabled for code execution.

Live Example Below


Ajax Test Example 3

Our Ajax call will add parameters to the URL call, depending on the choice made below. The server-side program will parse the arguments, and return the selected data type.

Ajax Request:

System Load
System Memory

Ajax Response:

Server Performance Data
   

Coming Up Next


In a upcoming final example, we look at Javascript libaries that simplify our handling of AJAX.

Source:

See Also: