Sunday, January 18, 2009

Capturing and Sending Key -Using AJAX

AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. By using the key object -XMLHttpRequest of AJAX, we can create a dynamic webpage which can make a request and get a response from web server in the background without reloading the page. The user may not even notice that it is communicating invisibly.
Let us discuss an example that captures and sends the key input using AJAX. This example is based on the one that can be found in W3Schools site. There will be three files- keyCapture.html, keyCapture.js, and keyCapture.php.
First, we will create an HTML page called "keyCapture.html" that have a DIV element to display the message returned by the server. All JavaScript will be put in a separate file.


<html>
<head>
<title>Key Capture</title>
<script src='keyCapture.js'></script>
</head>
<body>
<form>
Press a key to send to server.
<div id='text1' style="font-size: 40px; color:blue;">
</div>
</form>
</body>
</html>

Second, the JavaScript file called "keyCapture.js" is created to capture keyboard input and send to the server using AJAX. It is explained in details.

var xmlHttp;
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event) {
    var keyChar;
    if (document.all) {
        keyChar = String.fromCharCode(event.keyCode);
    }
    else if (document.getElementById) {
        keyChar = String.fromCharCode(key_event.which);
    }
    else if (document.layers) {
        keyChar = String.fromCharCode(key_event.which);
    }
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert("Your Browser does not support AJAX!");
        return;
    }
    var url = "keyCapture.php";
    url = url + "?keyC=" + keyChar + "&sid=" + Math.random();
    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function stateChanged() { if (xmlHttp.readyState == 4) { document.getElementById('text1').innerHTML = xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }

There are three main parts in this JavaScript file.
1. Creating XMLHttpRequest object
2. To define a function to handle the data returned by the server
3. To send off a request to the server


1. Creating XMLHttpRequest object
Depending on browser, the method for creating XMLHttpRequest object can be different. ActiveXObject is used in Internet Explorer and XMLHttpRequest JavaScript object is used in other browsers. The following JavaScript function can be used to deal with different browsers.
function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

In the function that wants to use the XMLHttpRequest object, we can just call this GetXmlHttpObject() function as
var xmlHttp
xmlHttp=GetXmlHttpObject();


If the object cannot be created, we can alert a message that AJAX is not supported.

if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 

2. To define a function to handle the data returned by the server
The following JavaScript define a function that will be called when the server response status has changed. The readyState property has five possible values (from 0 to 4) and it checks for request complete state (state value 4) before it process the response.


function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

When the server response status has changed, the function stored in onreadystatechange property will be called automatically. It must be defined in the function that initiates the XMLHttpRequest as

xmlHttp.onreadystatechange=stateChanged;


3. To send off a request to the server
When we submit a request using "GET" method, the ids of the fields and values of that fields are sent in the url e.g.,
http://youraddress.com/keyCapture.php?id1=val1
We will modify the url of our php script using that format and add another ramdom value to make sure that cached version is not returned.


var url = "keyCapture.php";
url = url + "?keyC=" + keyChar + "&sid=" + Math.random();

By using the open() method and the send() method of the XMLHttpRequest object, a request can be sent to the server. The first argument of the open method can be GET or POST. The second argument is URL of the server-side script and third one specifies to handle the request asynchronously.

xmlHttp.open("GET", url, true);
xmlHttp.send(null);


Third, the server side script called "keyCapture.php" will be written in PHP as follow.

<?php
//get the parameter from URL
$k=$_GET["keyC"];
echo "Received: " . $k;
?>

No comments:

Post a Comment

Comments are moderated and don't be surprised if your comment does not appear promptly.