Monday, June 1, 2009

SIMPLE AJAX EXAMPLES

In this article I don't want to show you the history of AJAX and discuss its pros and cons, but only focus on how to create a basic working AJAX - PHP communication.

The only important thing at the moment is that AJAX uses JavaScript so it need to be enabled in your browser to successfully complete this tutorial.

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. ( The example maybe not very useful but I think it is acceptable at this level. )

So let's list what we need to do:

* Listen on key-press event on the input field.
* In case of key-press send a message to the PHP script on the server.
* Process the input with PHP and send back the result.
* Capture the returning data and display it.

Our html code is very simple it looks like this:

Code:

1.
2.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3.

4.

5.

6.
Ajax - PHP example
7.

8.

9.

10.

11.


12.
Input text:
13.
Output text:
14.

15.

16.


Javascript F1

As you can see there is a doWork() function which is called in every case when a key is up (a key was pressed). Of course you can use any other supported events if you want.

But what is this doWork() and how we can send messages to the server script? On the next page you will find the answers.

Step 2 - Sending data to PHP with Ajax

Ajax PHP tutorial

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.

However creating this object is bit triky as the browser implement it various ways. If you don't want to support the quite old browsers we can do it as follows:

Code:

1.
// Get the HTTP Object
2.
function getHTTPObject(){
3.
if (window.ActiveXObject)
4.
return new ActiveXObject("Microsoft.XMLHTTP");
5.
else if (window.XMLHttpRequest)
6.
return new XMLHttpRequest();
7.
else {
8.
alert("Your browser does not support AJAX.");
9.
return null;
10.
}
11.
}

Javascript F1

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:

Code:

1.
// Implement business logic
2.
function doWork(){
3.
httpObject = getHTTPObject();
4.
if (httpObject != null) {
5.
httpObject.open("GET", "upperCase.php?inputText="
6.
+document.getElementById('inputText').value, true);
7.
httpObject.send(null);
8.

9.
}
10.
}

Javascript F1

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:

Code:

1.
// Implement business logic
2.
function doWork(){
3.
httpObject = getHTTPObject();
4.
if (httpObject != null) {
5.
httpObject.open("GET", "upperCase.php?inputText="
6.
+document.getElementById('inputText').value, true);
7.
httpObject.send(null);
8.
httpObject.onreadystatechange = setOutput;
9.
}
10.
}

Javascript F1

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:

Code:

1.
// Change the value of the outputText field
2.
function setOutput(){
3.
if(httpObject.readyState == 4){
4.
document.getElementById('outputText').value
5.
= httpObject.responseText;
6.
}
7.

8.
}

Javascript F1

Now the client side is ready let's implement the server side.

Step 3 - PHP code and the complete AJAX example

Ajax PHP tutorial


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:

Code:

1.
2.
if (isset($_GET['inputText']))
3.
echo strtoupper($_GET['inputText']);
4.
?>

Javascript F1

That's really short, isn't it?

At least you can find the complete client and server code below.

Client:

Code:

1.
2.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3.

4.

5.

6.
Ajax - PHP example
7.

8.

9.

10.

11.

46.

47.

48.
Input text:
49.
Output text:
50.

51.

52.


Javascript F1

Server:

Code:

1.
2.
if (isset($_GET['inputText']))
3.
echo strtoupper($_GET['inputText']);
4.
?>

0 comments:

Post a Comment