How to write an AJAX application

This is a very simple example of how to connect to a remote address and retrieve text. AJAX allows you to build user-friendly web applications that do not require a browser refresh to retrieve and display dynamic data.

Within the head section of your document, or in a javascript include, you will need to add a function that retrieves the XMLHttpRequest object.

function getNewHTTPObject() {
	var xmlhttp;

  /** Special IE only code ... */
  /*@cc_on
  @if (@_jscript_version >= 5)
    try
    {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
      catch (e)
    {
    try
    {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
      catch (E)
    {
      xmlhttp = false;
    }
  }
  @else
    xmlhttp = false;
  @end @*/

  /** Every other browser on the planet */
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
  {
    try
    {
      xmlhttp = new XMLHttpRequest();
    }
    catch (e)
    {
      xmlhttp = false;
    }
  }

  return xmlhttp;
}

You can then create a function to retrieve a specific URL, or get creative and accept a URL as a parameter for more flexibility. It can be a static text or XML document, or a script on an application server (PHP, JSP, ASP, Cold Fusion, Perl, etc.).

  // instantiate HTTP object
  var xmlHttp = getNewHTTPObject();

  function getDynamicData()
  {
    var url = "/path/to/some/file.xml";
    // or you can set to http://domain/script.php

    xmlHttp.open('GET', url, true);  // or you can send POST
    xmlHttp.onreadystatechange = callbackFunction;
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.send(null);
  }

Lastly, as you can see in this above function, you want to create a function that handles the response data when it is available. As you can see, the xmlHttp.onreadystatechange = someHandlerFunctionName or as defined above, callbackFunction. Below I simply assigned the response to a variable and for testing purposes, I used javascript’s alert function to display the contents of the text file I pointed the application to.

  function callbackFunction()
  {
    if (xmlHttp.readyState != 4)
      return;

    var result = xmlHttp.responseText;

    // return response as alert message for testing
    alert(result);
  }

All of the above would be in the HEAD section of your document. You can then add a link or form that invokes the javascript function, getDynamicContent() and it should display an alert message with the remote file contents. From here, you can get more and more complext or add custom functions to get specific content and/or serialize your requests into XML and deserialize the responses. It is a very powerful tool and if used correctly, you can create applications that are as user-friendly as desktop software.

Sending and XML request as POST:
Thanks: http://www.w3schools.com/dom/dom_http.asp

The example below was described at w3schools.com as a way to retrieve an XML document and send it to a dynamic script to parse and manipulate the XML. Note the third parameter (false) instead of (true) like above. This is the toggle between synch/asynch modes. Be careful when using synch (false) as it can result is application hanging. The above demonstration shows how to handle asynchronous implementations which is recommended.

xmlHttp.open("GET", "note.xml", false)
xmlHttp.send()
xmlDoc=xmlHttp.responseText

xmlHttp.open("POST", "some_script.php", false)
xmlHttp.send(xmlDoc)
document.write(xmlHttp.responseText)

See the dynamic calendar to the right. It leverages AJAX to allow retrieval of dynamic data without requiring a page refresh.

Happy coding!

1 Votes | Average: 5 out of 51 Votes | Average: 5 out of 51 Votes | Average: 5 out of 51 Votes | Average: 5 out of 51 Votes | Average: 5 out of 5 (1 votes, average: 5 out of 5)
Loading ... Loading ...


One Response to “How to write an AJAX application”

  1. Mike Sparr Says:

    I see that my blog escapes the double quote characters with the \ slash. Disregard this if you were planning on copy/paste!

Leave a Reply

You must be logged in to post a comment.