PHP with AJAX – Introduction

As I am celeberating my fifth year in a row working with PHP. It has been a great experiece, and i remember those days of PHP where it was revolving OOP concept to the latest ones which puts PHP in a place competiting with JAVA, dotnet and others. Anyway lets start as usual in RajiniKanth style.

Before going further… let me put what’s actually PHP and Ajax are all about.

PHP – > Taken from PHP website.

PHP(recursive acronym for “PHP: Hypertext Preprocessor”) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

AJAX — > From the Web

Ajax, or AJAX (Asynchronous JavaScript and XML), is a group of interrelated web development techniques used to create interactive web applications or rich Internet applications.

Lets start with some coding, so that you can put your speakers loud enough hearing RajiniKanth’s music as its going to be damm sweet and easy while we go through.

<?php
session_start();
$arrayNames = array(‘Preeti’,'Kajol’,'Vinoth’,'Nayantara’,'Sandya’,'Priya’,'Reenga’);

if(in_array($_GET['name'], $arrayNames)) {
echo ‘1′;
}
else {
echo ‘0′;
}
?>

You are starting the session initially, with this you are declaring array of names and storing it in a variable $arrayNames. if the names are available, we print out 1 and else its 0.

Now a Question might araise how are we checking and where are we. Wait dude… check down below which you will explain you the rest. For now remember the $_GET['name']. We are getting this ID from the indexpage and then checking it with the list of names here and printing one or zero based on that.

Let me explain each and every line, so it will make more clear on whats happening here. Don’t worry amigos, you will get a example at the very end. RajiniKanth’s movie always ends in a happy climax.

var ajaxObj=false;

We set the ajaxObj as false by defual and later it changes.

function ajaxMethod(url){
if(window.XMLHttpRequest){
ajaxObj= new XMLHttpRequest();
if(ajaxObj.overrideMinmeType){
ajaxObj.overrideMinmeType(‘text/xml’);
}
}

We are then moving to this function where we are checking what the browser is and then creating the required Object. Let me go further deeper.

function ajaxMethod(url){

Name of the function and it holds a parameter url which will be passed during the time of function call.

if(window.XMLHttpRequest){

If the browsing window is Firefox , Safari or IE 7.0 then we get here and then create a new XMLHttpRequest object. So what is this XMLHttpRequest?

ajaxObj= new XMLHttpRequest();

XMLHttpRequest (XHR) is a DOM API that can be used by JavaScript and other web browser scripting languages to transfer XML and other text data between a web server and a browser.

if(ajaxObj.overrideMinmeType){
ajaxObj.overrideMimeType(‘text/xml’);

The older version of Mozila needs some help from our coders to understand the Request which we are passing. The overrideMimeType will force the XMLHTTPRequest to parse it as XML anyway, if the server does not support test/xml content type header.

else if(window.ActiveXObject){
try{
ajaxObj= new ActiveXObject(“Msxml2.XMLHTTP”);
}catch (e){
try{
ajaxObj= new ActiveXObject(“Microsoft.XMLHTTP”);
}catch(e){}
}
}

Here we are checking if its Microsoft Internet explorer 6.0 and then creating the new ActiveXObject. Don’t worry though the process is same as above. There are few terms which would be nice if its also explained. Let me first go with ActiveXObject.

The ActiveXObject is use to enable and return a reference to an Automation object.An object that is exposed to other applications or programming tools through Automation interfaces. People say using ActiveXObject is dangerous as it allows access to operating system from outside the browser sandbox.

Msxml2.XMLHTTP and Microsoft.XMLHTTP

Actually to say there is no difference, Microsoft decided to change the namespace and they both will instantiate the same version of MSXML object which could be of any versions 2, 2.6 or 3.0

if(!ajaxObj){
alert(“your browser does not support”);
return false;
}

Do we need explantion? yes if this prints out then make sure that the version you use does not support. Upgrade to the newer version. I would say IE 7.0 or IE 8.0 beta.

ajaxObj.onreadystatechange = ajaxRes;
ajaxObj.open(‘GET’, url, true);

ajaxObj.send(null);
return true;
}

onreadystatechange event handler is fired when the state is 4. This property is an event handler which is triggered whenever the state of the request changes. The states run from zero (uninitialized) through to four (complete).

ajaxObj.open(‘GET’, url, true);
ajaxObj.send(null);

The open method here makes the request to the server with the url which is passed during the function call time. It takes three parameters. The first one is the request type which is either GET or POST. The second one is the url of the server side process and the third defines whether the call will be asynchronous (true) or synchronous (false).

Asynchronous means the processing will happen without waiting for the server side retrieval to complete and where as synchronous call would stop all other processing and wait for the response from the server.

the event handler is defined and we are ready to send our request to the server which is done by the send method.

function ajaxRes() {
if(ajaxObj.readyState == 4) {
if(ajaxObj.status == 200) {
if(ajaxObj.responseText == ‘1′){
alert(‘Its seems to be ok’);
}
else {
alert(‘I think you are not known’);
}
}
else {
alert(‘it seems there is some other error’ + ajaxObj.status.toString() + ‘.’);
return;
}
}
}

The readyState property holds the status of the server’s response. Each time the readyState changes, the onreadystatechange function will be executed.

0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

The data sent back from the server can be retrieved with the responseText property.

The Tutorial has come to finale, and it seems the hands are itching to test the code and check for a demo. As i said, RajiniKanth fans or movie never dissappoints anyone.

Download the Code and Check the Demo Here.

Popularity: 8% [?]

About the Author

Vinothbabu has written 24 stories on this site.

In short, my name is Vinoth babu { perra kettala summa authrithala } a UI expert from India, Chennai.

One Comment on “PHP with AJAX – Introduction”

  • ?a?ap wrote on 31 May, 2009, 8:26

    ????? ???? ?????????. ? ??????????? ??????.

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 HTTPguru. All rights reserved.

Our Partners:
WebHosting Jobs| UI expert | Packet Sniffer  | Mobile Home Refinancing  | Laptop LCD screens | CSS Creator| Exchange Hosting| Compare cable companies| Usa online casino | vps | Coupon Codes