Ajax

Derek Bridge

Department of Computer Science,
University College Cork

Ajax

Aims:

HTTP requests

A browser sends an HTTP request to a server...

But a client-side script can also send a HTTP request

Syncrhonous response handling

In the case of synchronous response handling...

Asynchronous response handling

In the case of asynchronous response handling...

Class exercise: Asynchronous response handling is a little more complicated to program, but synchronous response handling has a severe disadvantage. What is it?

XMLHttpRequest objects

Summary of what your client-side script needs to do in order to send an HTTP request:

  1. Create the request object
  2. Register a function that will handle the response (assuming asynchronous response handling)
  3. Specify the URL and the HTTP method (e.g. GET or POST)
  4. Optionally, specify any special headers that are to be sent
  5. Send the request

XMLHttpRequest example

  1. Create the request object
    var request = new XMLHttpRequest();
  2. Register a function that will handle the response (assuming asynchronous response handling)
    request.onreadystatechange = ...some function...;
  3. Specify the URL and the HTTP method (e.g. GET or POST)
    request.open("GET", url, true);
  4. Optionally, specify any special headers that are to be sent, e.g.
    request.setRequestHeader("User-Agent", "XMLHttpRequest");
    request.setRequestHeader("Accept-Language", "en");
  5. Send the request
    request.send(null);

The response

Typical function to handle the response

function handle_response()
{
   // Check that the response has fully arrived
   if ( request.readyState == 4 )
   {
      // Check the request was successful
      if ( request.status == 200 )
      {
         // do whatever you want to do with 
         // request.responseText or request.responseXML
      }
   }
}

Ajax

Ajax...

What's the idea...

History

Ajax example

The PHP script: check_name_available.php

<?php 
 // Cleans a string, $str, to make it suitable for querying/
 // storing in databases.
 // Specifically, it removes leading and trailing spaces and 
 // adds slashes to escape single quotes, double quotes and 
 // backslashes.
 function clean($str)
 {
	return mysql_real_escape_string(trim($str));
 }
 
 // Include the PHP to connect to the database
 include('dbconnect.php');
 // Get the user name
 $user_name = clean($_GET['user_name']);
 // Check whether this user name is in use
 $sql = "SELECT * FROM users WHERE user_name = '{$user_name}'";
 $dbresult = mysql_query($sql);
 if ( ! $dbresult )
 {
    die('Error in query ' . mysql_error());
 }
 if (mysql_num_rows($dbresult) > 0) 
 {
    // User name is already in use
    echo "false";
 }
 else
 {
	// User name is available
	echo "true";
 }
?>

The client-side JavaScript: check_name_available.js

if ( window.addEventListener )
{
   window.addEventListener("load", init, false);
}
else if ( window.attachEvent )
{
   window.attachEvent("onload", init);
}

function init()
{
   document.getElementById("nameField").onkeypress = set_link;
   document.getElementById("checker").onclick = check_name_available;
}

function set_link()
{
   document.getElementById("checker").innerHTML =
      '<a href="#">Check name is available</a>';
}

function check_name_available()
{
   var url = "check_name_available.php?user_name=" + 
         document.getElementById("nameField").value;
   var request = new XMLHttpRequest();
   request.onreadystatechange = function()
   {
      // Check that the response has fully arrived
      if ( request.readyState == 4 )
      {
         // Check the request was successful
         if ( request.status == 200 )
         {
            if ( request.responseText == 'true' )
            {
               document.getElementById("checker").innerHTML = 
                  "Name available";
            }
            else
            {
               document.getElementById("checker").innerHTML = 
                  "Name not available";
            }
         }
      }
   }
   request.open("GET", url, true);
   request.send(null);
}

All that glitters is not gold: problems with Ajax