Monday, November 1, 2010

Implementing AJAX

In the last post, we have learnt that what is AJAX.
Now in this post, we will implement it using PHP.
 The only important thing at the moment is that AJAX uses JavaScript so it needs to be enabled in your browser to successfully implement it.
To demonstrate the AJAX PHP connection we will create a very simple form with 2 input fields.
In the first field you can type any text and we will send this text to our PHP script which will convert it to uppercase and sends it back to us. At the end we will put the result into the second input field.
Let us see some simple html code:
<html>
<head><title>Ajax - PHP example</title>
</head>
<body>
<form name="testForm">
 Input text: <input type="text"  onkeyup="doWork();" name="inputText" id="inputText" />
 Output text: <input type="text" name="outputText" id="outputText" />
 </form>
</body>
</html>
Observe the above code. All except onkeyup=”doWork();” is familiar to you. The doWork() is a function which is called in every case when a key is up (a key was pressed). But what is this doWork() and how it works?
Before the explanation of the doWork() function we first need to learn a more important thing. To make a communication between the client and the server, the client code needs to create a so called XMLHttpRequest object. This object will be responsible for AJAX PHP communication.
See the code:
function getHTTPObject()
{
if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");

else if (window.XMLHttpRequest)
return new XMLHttpRequest();

else
{
alert("Your browser does not support AJAX.");
return null;
  }
}  
XMLHttpRequest object- It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script. The data might be received from the server as XML text or as plain text.
Create an XMLHttpRequest Object:
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
xmlhttp=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

window.ActiveXObject and window.XMLHttpRequest are used to judge the browser.
Ok, now we have the XMLHttpRequest object, so it's time to implement the business logic inside the doWork() function.
First of all we need to get a valid XMLHttpRequest object. If we have it then we can send the value of the inputText field to the server script. We do this by composing an URL with parameter, so in the PHP script we can use the $_GET super-global array to catch the data. As next step we call the send() function of the XMLHttpRequest object which will send our request to the server. At the moment our doWork() function looks like this:
function doWork()
{
 httpObject = getHTTPObject();
    if (httpObject != null)
{        httpObject.open("GET", "upperCase.php?inputText="                        +document.getElementById('inputText').value, true);
        httpObject.send(null);
    }
}
The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open method. This method must be invoked prior to the actual sending of a request to validate and resolve the request method, URL, and URI user information to be used for the request. This method does not assure that the URL exists or the user information is correct. This method can accept up to five parameters, but requires only two, to initialize a request.
The first parameter of the method is a text string indicating the HTTP request method to use
The second parameter of the method is another text string, this one indicating the URL of the HTTP request.
The third parameter, a boolean value indicating whether or not the request will be asynchronous,
The default value of this parameter should be assumed to be true. An asynchronous request ("true") will not wait on a server response before continuing on with the execution of the current script. It will instead invoke the onreadystatechange event listener of the XMLHttpRequest object throughout the various stages of the request. A synchronous request ("false") however will block execution of the current script until the request has been completed, thus not invoking the onreadystatechange event listener.
The fourth and fifth parameters are the username and password, respectively. These parameters, or just the username, may be provided for authentication and authorization if required by the server for this request.
To send an HTTP request, the send method of the XMLHttpRequest must be invoked. This method accepts a single parameter containing the content to be sent with the request. This parameter may be omitted if no content needs to be sent.
JavaScript: document.getElementById
If you want to quickly access the value of an HTML input give it an id to make your life a lot easier. The script above will check to see if there is any text in the text field "inputText". The argument that getElementById requires is the id of the HTML element you wish to utilize.
It's nice but how we can catch the response from the server? To do this we need to use an other special property of the XMLHttpRequest object. We can assign a function to this parameter and this function will be called if the state of the object was changed. The final code is the following:
function doWork()
{
 httpObject = getHTTPObject();
    if (httpObject != null)
{        httpObject.open("GET", "upperCase.php?inputText="                        +document.getElementById('inputText').value, true);
        httpObject.send(null);
        httpObject.onreadystatechange = setOutput;
    }
}
The last step on client side is to implement the setOutput() function which will change the value of our second field. The only interesting thing in this function that we need to check the actual state of the XMLHttpRequest object. We need to change the field value only if the state is complete. The readyState property can have the following values:
·         0 = uninitialized
·         1 = loading
·         2 = loaded
·         3 = interactive
·         4 = complete
So the setOutput() looks like this:

function setOutput()
{
if(httpObject.readyState == 4)
{
document.getElementById('outputText').value = httpObject.responseText;
  }
}
If the open method of the XMLHttpRequest object was invoked with the third parameter set to true for an asynchronous request, the onreadystatechange event listener will be automatically invoked for each of the following actions that change the readyState property of the XMLHttpRequest object.
  • After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1.
  • After the send method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object should be assigned a value of 2.
  • Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3.
  • Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4.
responseText will contain the response of the server in plain text by a conforming user agent, and the value is stored in outputText field.
Implementing the server side functionality is very simple compared to the client side. In the PHP code we just need to check the $_GET super-global array. Afterwards convert it to uppercase and echo the result. So the PHP code is this:
<?php
    if (isset($_GET['inputText']))
     echo strtoupper($_GET['inputText']);
?>
Description
string strtoupper ( string string )
Returns string with all alphabetic characters converted to uppercase.
So the complete client code is:
<html>
<head><title>Ajax - PHP example</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
function getHTTPObject()
{
if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");

else if (window.XMLHttpRequest)
return new XMLHttpRequest();

else
{
alert("Your browser does not support AJAX.");
return null;
  }
}  

function setOutput()
{
if(httpObject.readyState == 4)
{
document.getElementById('outputText').value = httpObject.responseText;
  }
}

function doWork()
{
 httpObject = getHTTPObject();
    if (httpObject != null)
{        httpObject.open("GET", "upperCase.php?inputText="                        +document.getElementById('inputText').value, true);
        httpObject.send(null);
        httpObject.onreadystatechange = setOutput;
    }
}
var httpObject = null;
</script>
  <form name="testForm">
     Input text: <input type="text"  onkeyup="doWork();" name="inputText" id="inputText" />
     Output text: <input type="text" name="outputText" id="outputText" />
  </form>
</body>
</html>
And the server code is:
<?php
    if (isset($_GET['inputText']))
     echo strtoupper($_GET['inputText']);
?>
Note:
To write javascript code, we start with <script language="javascript" type="text/javascript">
And end with <script>. And to write function we must write keyword ‘function’.

No comments:

Post a Comment