Advertisment

AJAX with PHP

author-image
PCQ Bureau
New Update

Now that you know how to use AJAX with ASP.NET (refer to Creating AJAX Pages with ASP.NET 2.0, page 83, October 2005), let us take you a step further. Similar to Web services and XML, libraries for AJAX are available for many programming languages, not excluding PHP. For a quick recap on what is AJAX, it allows a JavaScript on a Web page to call a server-side script. The server-side script returns the result and uses a callback mechanism to call a JavaScript function on the same Web page. This JavaScript function can then display the results on the Web page. 

Advertisment

All this happens without a page reload or refresh, which is the USP of AJAX. Note that this kind of facility is not new and could be implemented using remote scripting. Refer to the article Remote Scripting with PHP at the URL

https://www.pcquest.com/content/search/showarticle.asp?arid=52045.  

Direct Hit!
Applies to: PHP 5 developers
USP:

Build dynamic data enabled websites without page reloads
Primary Link:

www.php.net, http://sven-jacobs.de/wiki/AJASON
Google keywords:

ajax php 5 
On PCQEssential CD: Developer\AJASON

But with AJAX, things have become more standardized and easier. Compare the remote scripting code mentioned in this

article with the code that we will write in this article, and you will conclude that the code is easier to write, maintainable and is

object oriented! 

Advertisment

In this article we take up a typical example of a Web page consisting of two dropdowns-one for country and the second for states. Such dropdowns are typical to a registration form that asks for your details including your country and state. Upon the selection of a particular country, the states's dropdown must show the states in the selected country. We will first see how this is done traditionally and subsequently see how the same can be achieved with AJAX.

Database setup



We assume that you are running PCQLinux 2005 and have installed and set up MySQL. Refer to the article Your own Forum, page 60, March 2005, PCQuest. You will also need to install PHP 5.0 or above because we will use the object-oriented features of PHP 5 with the AJAX library. Refer to another article A Datagrid for PHP at the URL

https://www.pcquest.com/content0/search/showarticle.asp?arid=69130

to install PHP 5 on PCQLinux 2005. 

To learn about the object-oriented features of PHP 5, refer to http://in.php.net/zend-engine-2.php. Create a MySQL database named pcqdb using the 'mysqladmin -u root -p create pcqdb'

command. 

Advertisment

This spreadsheet (numsum.com) can be shared across the Web because it works on AJAX

When prompted, supply the password for the root MySQL (the one which you specified during the MySQL set up). Then issue 'mysql -u root -p pcqdb' and when prompted, supply the password as before. This will drop you into a mysql>prompt. At this prompt, create two tables named country and state as:

create table country (id int auto_increment, name varchar(50), primary key(id));



create table state (id int auto_increment, name varchar(50), country int, primary key(id));

Advertisment

Populate the tables with country and state data as:

insert into country (name) values ('India');



insert into country(name) values('US');


insert into state(name,country) values ('Delhi',1);


insert into state(name,country) values('Haryana',1);


insert into state(name,country) values ('Michigan',2);


insert into state(name,country) values('California',2);



The traditional way



We have uploaded a simple PHP script in the Developer section of PCQuest Forums

( http://forums.pcquest.com).Download the script and open it in a text editor to view. This is how a typical Web application is written to achieve the country-state drop-down logic. 

Advertisment

zimbra provides web-based, e-mail, calendaring and collaboration package through AJAX

Note that we have made full use of the object-oriented capabilities of PHP 5. The first select list named 'country' calls the form.submit(), which submits the HTML form, whenever a user selects an option from the dropdown. Upon submit, the page is reloaded. This time the following condition becomes true and the state select list is populated. 

if(isset($_POST<"country">))



Note that the function getCountries( ) and getStates( ), return the result set as an array. Substitute 'secret' in the above code with the password for the MySQL root user in your case. Save the above file as register.php in /var/www/html. Type in the URL

http://localhost/register.php. Select a country from the dropdown, upon which the corresponding states will show.

Advertisment

Notice the two pitfalls:

  • The page reloads each time you select a country
  • The selected country in the 'country' dropdown changes back to the default upon reload leaving no clue to the user on which country he selected.

These two pitfalls can be overcome using AJAX. Lets see how.

Advertisment

The AJAX way



You can find the AJAX library for PHP called AJASON on this month's PCQEssential CD. Extract the AJASON archive with the

'tar -jxvf AJASON_09.tar.bz2' command. This will produce a directory named AJASON. Copy the directories named php and javascript found under AJASON to /var/www/html. Using AJASON library is simple. For doing this, follow the steps given below.

  • Include the AJAX specific PHP and Javascript
  • Construct the AJAX object 
  • Register the class and the method with the AJAX object (getStates( ) in our case)
  • Specify the PHP script which will be called server.php in our case 
  • Call the method, registered with the AJAX object, using Javascript

We'll put the Register class and the function to create AJAX object in the common.php file. Substitute 'secret' with a password, and save the following code as common.phpin/var/www/html: 



require_once('php/Ajax.php' );



class Register{


public static $conn;


public static function getCountries( ) {


$query = "select id,name from country order by name";


$rs = mysql_query($query,self::$conn);


$result = array();


$i=0;


while($row=mysql_fetch_array($rs,MYSQL_ASSOC))


$result<$i++>=$row;


return $result; 


}


public static function getStates($country){


$query = "select id,name from state where country=$country order by name";


$rs = mysql_query($query,self::$conn);


$result = array(); 


$i=0;


while($row=mysql_fetch_array($rs,MYSQL_ASSOC))


$result<$i++>=$row;


return $result; 


}


}


REGISTER::$conn = mysql_connect("localhost","root","secret");


mysql_select_db("pcqdb",REGISTER::$conn);


function getAjaxObject()


{


$ajax = new Ajax();


$ajax->registerMethod("Register","getStates");


$ajax->setOption( Ajax::HandlerOption, 'server.php' );


return $ajax; 


}


?>





























The AJAX server



With AJAX, we have to think in terms of the client server technology. Here the client is the Web page containing the Javascript which calls the PHP script and the server is this PHP script. The client and the server share a common AJAX object which is created in the function named getAjaxObject( ) in the above code.With the method named registerMethod( ) of AJAX, you specify the class and its function which will be callable from the AJAX client. The syntax of the method is '$ajax->registerMethod("","");'. Subsequently we use the setOption( ) method to specify the PHP script to be called-which is server.php in this case. Below is the code for server.php. Save the file in /var/www/html as:



require_once( 'common.php' );



$ajax = getAjaxObject(); 


$ajaxServer = $ajax->getServer();


if ( $ajaxServer->isRequest() ){


echo $ajaxServer->handleRequest();


}


?>




Note the inclusion of common.php at the top. The above code creates a server object for AJAX and if the server receives an AJAX request from the client, the handleRequest( ) method will invoke the specified method, (getStates) and return the response to a JavaScript function specified by the client (see the next section). 

The AJAX client



Below is the code for the client called ajaxregister.php.



require_once( 'common.php' );



$ajax = getAjaxObject(); 


$ajaxClient = $ajax->getClient();


?>




































Country:







State:










At the beginning of the code we create a AJAX client in the same way as we created the server. Then we include a couple of JavaScript files namely jason.js and ajax.js. Subsequently, the line 

getJavaScript()); ?>

emits some JavaScript code to hand over the AJAX request to the server. Now let's look at the syntax of the JavaScript which will execute the method getStates( ). Note that, now instead of calling form.submit( ) on 'onChange', we are calling a JavaScript function as:

x_Register.getStates(this.options.value,displayStates);

The syntax of the above statement is:

x_.(' ','');

Also note that we have specified displyStates( ) for the callback function. This means that the displayStates( ) will be executed after receiving response from the server. The response from the server (a two-dimensional array in our case) will be available as the parameter (called result in our case) to the displayStates( ) function. Subsequently, if you go through the body of the displayStates( ) function, we are using standard JavaScript functions to populate the state dropdown with the response from the server. 

Type in the URL http://localhost/ajaxregister.php. Select a country from the dropdown, upon which the corresponding states will show without a page reload. And since the page does not reload, the selected country does not change to the default. 

Shekhar Govindarajan, IT4Enterprise

Advertisment