Beginning Ajax with PHP

[printfriendly]

Beginning Ajax with PHP part1

Nowdays, you can find AJAX topic everywhere. Yes, this method brings more advantage in internet word. Some people say AJAX is not new technology. It just a method. Other people say it is a technology. In this post, we talk about AJAX in preview.

AJAX is an acronym for Asynchronous JavaScript and XML. For me, it mean simple “empowered JavaScript”. What that mean? Mmm.. before talk what AJAX exactly, do you ever see (or taste) Yahoo Mail! Beta Version? Or Gmail (not HTML version)? At that web page, without reload full page, we can jump between pages.

It is a technique use JavaScript as client side to make background server calls and retrieve additional data as needed. It update certain portions of page without causing full reloads. This is little example web that apply AJAX:

  1. Google Suggest, check it out at http://www.google.com
  2. Gmail, http://www.gmail.com
  3. Google Maps, http://maps.google.com

I think AJAX is smart web application. More responsive web page. I remember it is like ‘flash’! Yeah, we can build smart application like flash page. But, at AJAX, you don’t need install any extra modules. AJAX runs all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera. Following the anatomy of AJAX:

  1. JavaScript, is essential of AJAX. We use for Client Side function and use Document Object Model (DOM) to manipulate parts of HTML page.
  2. The XMLHttpRequest object enable JavaScript to access server asynchronously.
  3. Server side technology to handle the request that come from the JavaScript Client, example PHP.

Shortcut to AJAX

Now, we try to use Ajax in our simple application. First time, we will build simple ajax library. Then, we write page to load the ajax library. This is very basic application. You can still extend it for more complex web.

Ok, for this practice, we need 3 file (I create within www/test/ajax directory):

  1. ajax.js -> as ajax library
  2. test.php -> as main page
  3. home.html -> will be loaded as content

First, write below line codes within ajax.js

 


// JavaScript Document

function callAJAX(url,div)

{

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById(div).innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open("GET",url,true);

xmlhttp.send();

}

Explanation of Above Code:

The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

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:


variable=new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:


variable=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:


var xmlhttp;
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:


xmlhttp.open("GET", url,true);
 xmlhttp.send();

Method Description
open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not.method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous) send(string) Sends the request off to the server.
send(string) Sends the request off to the server.string: Only used for POST requests

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

  • A cached file is not an option (update a file or database on the server)
  • Sending a large amount of data to the server (POST has no size limitations)
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET

The url – A File On a Server

The url parameter of the open() method, is an address to a file on a server:


xmlhttp.open("GET",url,true);

The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can perform actions on the server before sending the response back).

Asynchronous – True or False?

AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async parameter of the open() method has to be set to true:

xmlhttp.open(“GET”,url,true);

Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.

With AJAX, the JavaScript does not have to wait for the server response, but can instead:

  • execute other scripts while waiting for server response
  • deal with the response when the response ready

Async=true

When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:

Async=false

To use async=false, change the third parameter in the open() method to false:


xmlhttp.open("GET","ajax_info.txt",false);

Using async=false is not recommended, but for a few small requests this can be ok.

Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async=false, do NOT write an onreadystatechange function – just put the code after the send() statement:


function callAJAX(url,div)

{

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("GET",url,false);

xmlhttp.send();

document.getElementById("div").innerHTML=xmlhttp.responseText;

}

Server Response

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

Property Description
responseText get the response data as a string
responseXML get the response data as XML data

The responseText Property

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it accordingly:

document.getElementById(“myDiv”).innerHTML=xmlhttp.responseText;

The onreadystatechange event

When a request to a server is sent, we want to perform some actions based on the response.

The onreadystatechange event is triggered every time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: “OK”
404: Page not found

In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.

When readyState is 4 and status is 200, the response is ready:


xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
     }
   }

Note: The onreadystatechange event is triggered four times, one time for each change in readyState.

Now, we create test.php, enter following codes:

<html>
<head>
<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
</head>
<body onload="callAJAX('home.html','displaydiv')">

<table>
<tr>
<td id="displaydiv"></td>
</tr>
</table>

</body>
</html>

last, we create home.html, enter following line code:


<h1>Welcome to Ajax World</h1>

 

Now, point your browser to http://localhost/ajax/test.php, you will get like this:

Beginning Ajax With PHP Test 1

Loading Web Content from Links

Now, we try build links in page. Then, from that links we call web content. This is basic and simple way to use ajax in our web. From this practice, we can see how Ajax works.

Ok, Create test2.php, enter following code:

<pre><html>
<head>
<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
</head>
<body onload="callAJAX('home.html','displaydiv')"><b>
<a href="#" onclick="callAJAX('home.html','displaydiv')">Home</a>
<a href="#" onclick="callAJAX('news.html','displaydiv')">News</a>
<a href="#" onclick="callAJAX('about.html','displaydiv')">About</a></b>
<table>
<tr>
<td id="displaydiv"></td>
</tr>
</table>

</body>
</html>

 

Create “news.html”, enter following test code:


<h2>news page test</h2>

 

Create “about.html” enter following test code:


<h2>about page test</h2>

 

 

Now, point your browser to http://localhost/ajax/test2.php. Try click link.

Beginning Ajax With PHP Example 2

Loading Preloader Animation Image

We add something that make user know ajax still works. We called preloader. It will help user to know where part of page will change. It also add more attractive to our web.

You can use many preloader like this:

Ajax freeloaderAjax freeloader2Ajax freeloader3Ajax freeloader4

Ok, we try to use it. Open test2.php. Replace with following code:

<html>
<head>
<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
</head>
<body onload="callAJAX('home.html','displaydiv' , '<center>
<img src=loading6.gif></center>')">
<a href="#" onclick="callAJAX('home.html','displaydiv', '<center>
<img src=loading6.gif></center>')">Home</a>
<a href="#" onclick="callAJAX('news.html','displaydiv', '<center><img
src=loading6.gif></center>')">News</a>
<a href="#" onclick="callAJAX('about.html','displaydiv', '<center><img
src=loading6.gif></center>')">About</a>
<table>
<tr>
<td id="displaydiv"></td>
</tr>
</table>

</body>
</html>

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
4 comments on “Beginning Ajax with PHP

Leave a Reply

Your email address will not be published. Required fields are marked *