COMP249: AJAX

Steve Cassidy

COMP249: Web 2.0 and AJAX

The Machine is Us/ing Us

AJAX

Javascript can modify the DOM of the current page:

function replacetext(id, text) {
   document.getElementById(id).innerHTML = text   
}
function setTextArea(id, text) {
   document.getElementById(id).value = text;
}
...
<button onclick="replacetext('demo', 'Hello World')">
   Click Me!
</button>
 
<button id="demo2" onclick="setTextArea('txt', 'Hello World')">
   Click Me too!
</button>
      

XMLHttpRequest

      
if (navigator.appName == "Microsoft Internet Explorer") {
    http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
    http = new XMLHttpRequest();
}      

XMLHttpRequest

XMLHttpRequest

  function updatedemo() {
      if(http.readyState == 4) {
          replacetext('demo', http.responseText);
      }
  }

  http.onreadystatechange=updatedemo;
  http.open("GET", "test.txt");
  http.send(null);  
     

XMLHttpRequest: readyState

readyState is a property of the request object that can have one of four values:

We generally wait for readyState==4.

XMLHttpRequest: Properties

Other properties of XMLHttpRequest:

XMLHttpRequest POST Example

For a POST request, we need to set the MIME type and then send the data:

http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.open("POST", "/cgi-bin/doit.py");
http.send("name=Steve&age=21");
      

XMLHttpRequest: Handling XML Responses

var xmlDoc = http.responseXML
/* use regular XML DOM methods on xmlDoc */
text = xmlDoc.getElementsByTagName('key').item(0).data;      
      

Security Issues

Toolkits

jQuery in brief

$("p.special").click(function() { alert("Hello"); });
$("a").addClass("test").show().html("foo");
       

jQuery Example

  <html>
  <head>
    <script type="text/javascript" 
             src="path/to/jquery.js"></script>
    <script type="text/javascript">
 $(document).ready(function(){
   $("a").click(function(){
     alert("Thanks for visiting!");
   });
 })
    </script>
  </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
  </body>
  </html>
      

jQuery Examples

Now write some code...