Tuesday, 21 July 2009

AJAX Reference

This is more a quick reference for me than anything else. Below is a CFML'ed up version of the AJAX tutorial from w3schools.com.

index.cfm

<html>
  <head>
    <script src="js/script.js" type="text/javascript"></script>
  </head>
  <body>
    <form name="myForm">
      Name: <input id="username" type="text" onkeyup="ajaxFunction();" />
      Time: <input id="time" type="text" />
    </form>
  </body>
</html>

time.cfm

<cfoutput>#timeFormat(now())#</cfoutput>

script.js

function ajaxFunction() {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    alert("Your browser does not support XMLHTTP!");
  }
  
  xmlhttp.onreadystatechange=function() {
    if(xmlhttp.readyState==4) {
      document.myForm.time.value=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET", "time.cfm", true);
  xmlhttp.send(null);
}

Prototype

And to achieve the same thing with the prototype library:

index.cfm

  ...
  <head>
    ...
    <script src="js/prototype-1.6.0.3.js" type="text/javascript"></script>
    ...
  </head>
  ...

time.cfm - as above

script.js

function ajaxFunction() {
  var request = new Ajax.Request("time.cfm", {
    method: "get",
    onComplete: function(xmlhttp){
      $('time').value = xmlhttp.responseText;
    }
  });
}