36 sites, 11,103 entries and counting...     Get a free blog; Join a Weblog Network!
Top

Securing ajax request

September 30, 2008

Secure your request is very important since it will prevent someone to steal or to get in your datas. Following a way to do it.
You have to be able to generate a secure key from the server and after to affect the key the following code : $_SESSION[’Env_UserSession’][’AjaxKey’] = $key_sec
From the customer side, the key should be available via javascript and it can be a source of an hidden string. During the ajax request, get back the key and to transmit it to the ajax parameters. When the request is launched, you have to control from the server that the key exists and to verify it with the one saved in the session (this one should be verify before to generate the ajax content to the customer).
When you have to control the server, you have to verify very well POST or GET exists because if it is empty, it can be someone try to steal the content. If all are ok, you can deliver the content without any danger.

Tips for ajax

September 17, 2008

I will propose 3 tips about ajax that i used.

- Add a slideshow in your web site. I propose you to try SmoothSlideShow.SmoothSlideShow is very easy to use, you can install it for free and it is very cool for pictures.

- Debugging drafts with Firebug. Firebug is a plugin for Firefox on which you can edit, debug, and monitor CSS, HTML, AJAX and JavaScript live in any web page.

- Creating easily some frameworks with those 4 tools. Mootools allows you to create some effects easily. Yahoo UI library allows you to create a thousand of interfaces and effects. Dojo allows you to create widgets, graphs and etc. OpenRico allows you to create animations, ajax, drag and drop…

I hope you will have fun with those tools like me.

How to create a form in a simple click

September 9, 2008

It is very difficult to create a form, at least for people who have no knowledge about programming. There is a web site which proposes for those people to create a form in a very easy way.

You just have to go to this site http://www.jotform.com , create an account (it s free totally) and after log in just choose one of the assistants to create your own form. You can configure totally your form and the application is very simple and easy to use.

The bad point is that the generated code is not very clean for some form but what is the most important point, that we get the good result.

Ajax Alternatives?

July 16, 2008

Its difficult to claim perfection in anything, even Ajax. While Ajax has enhanced the web experience for many users, and there is not shortage of people constantly praising its merits, it is perhaps no longer the newest standard. Sure, it allows relatively easy integration of interactive elements in web pages, but is it really all that powerful and versatile as is often claimed?

There are three major standards for the development of Rich Internet Applications: Ajax, Java, and Flash. None of these are perfect solutions, but each has its own advantages over the others.

This is where the choice comes in. Ajax is at its strongest for such applications as information submission, but weaker when applied as a true asynchronus system.

On the other hand, Ajax is probably the most versatile of the options available. While not always the most efficient, it can get the job done. Many of its disadvantages can be blamed on web browsers not following standards and not being optimized for the desired degree of interactivity.

BARBER OF UNCOUTH TOWN

June 28, 2008

I thought that shaving pangs of silent victims must be rumour
But then I reviewed my stand in a good humour
One incident changed my convictiona s it was a fact stranger than fiction
Once before facing an interview
I wanted to revamp my unkempt view
So went to a Barber’s shop
He was busy shaving a cop
When the cop left the Saloon
The barber looked at me as a king look at a Hoon
People rush to me with overgrown weeds
And then for speedy shaving pleads
How am I to entertain such requests
Of my unsolicited guests?
See from cheeks to chin you are covered with hair
Such clients to my shop are the rarest rare
My blades will go blunt while bushwhacking this jungle
Saying this he inserted the blade into razor
And wildly wielded his weapon to my displeasure
After sometime blood rushed from so many cuts-
He said don’t worry your beard is very hard
So your face with care I safeguard
He took a slab of an Alam and rubbed on my face
And said now you are free from infection in any case
When I rose from the chair
In the mirror on my face I stare
I looked like a wounded soldier of Panipat
With on every inch of skin a bleeding cut
The Interview committe would think
That I have directly rushed from the boxing ring

CRETIVITY ORIGINALITY AND INSIGHT

June 27, 2008

Creativity and originality are two most precious things because these qualities distinguish a genius from ordinary mortals.Looking at the falling apple Newton thought why it did not go up.This critical thinking is the original way of looking at an ordinary day today
2
happening.Einstein’s Theory of relativity and his equation E=MC are the greatest instances of creative thinking and originality.Thus Creativity and originality consists in novel way of looking at things.Creativity and originality are not restricted to a particular area of human activity.Shall we consider Pablo Picasso and Salvador Dali lesser mortals than Einstein and Newton? Certainly not because what the creativity displayed by Dali and Picasso in the area of Fine Arts was by no means of less intensity than the creativity displayed by Einstein and Newton in the field of science.In other words whatever excellence was achieved by Einstein and Newton in the field of science the same degree of excellence was achieved by Dali and Picasso in the field of fine arts.Other important faculty of a genius is insight.Ordinary mortals have lot of information but no insight.Dr Louis Pasteure’s invention of anti-rabies vaccine(a viral vaccine) at atime when electronic microscope was not discovered is the rarest rare instance of insight.Insight,creativity and originality can be achieved by perseverance and constant practice.The first and foremost requirement of for acquiring creativity and insight is never borrow ideas and be an original thinker.Never act blindly on other people’s advise but take all important decisions on your own using your own brain.

Getting Started with Ajax

June 27, 2008

The start of 2005 saw the rise of a relatively new technology, dubbed “Ajax” by Jesse James Garrett of Adaptive Path. Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the nonstandard XMLHttpRequest() object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including XML, HTML, and even text files. Ajax’s most appealing characteristic, however, is its “asynchronous” nature, which means it can do all of this without having to refresh the page. This allows you to update portions of a page based upon user events and provides one of the cornerstones of Rich Internet Applications (RIA) referred to in discussions of “Web 2.0.”

The DOM plays into Ajax in a number of ways. How you use the DOM depends a good deal on how you handle the content returned from the server. You can treat the con­tent as simple text using the responseText property of the server response, or you can treat it as XML using responseXML. Assuming the content you pull back from the server is an (X)HTML snippet and you’ve gotten it as responseText, you could drop that content into a particular spot on the page using innerHTML. On the flip side, if the content you pull back is XML and you’ve gotten it as responseXML, you can traverse its DOM, cherry-picking or performing functions on the elements, attributes, and text nodes.

This probably sounds very confusing, but it is pretty easy once we go over a few simple examples. For these examples, we are using the XHConn library for simplifying our interaction with XMLHttpRequest(). The XHConn library is freely available at xkr.us/code/javascript/XHConn/ and allows simple access to XMLHttpRequest() by creating a new XHConn object and then initiating its connect() method as you will soon see.

As with the DOM Scripting examples (above), for a blow-by-blow of what the script is doing, read the JavaScript comments.

Example 1: Ajax with innerHTML
For a simple innerHTML-based Ajax example, we’ll create a quasi-functional address book application. We’ll start with the XHTML page (line wraps marked » —Ed.):

Simple Ajax Address Book


Please Choose a Person

Choose Someone
Bob Smith
Janet Jones



As you can see, we have a simple form with a select, from which to choose a person. Again, we are providing a fallback action for the form, in case our JavaScript cannot run. Below the form, we have a simple pre element that will be displaying the address information from the database.

And now for the JavaScript. Basically, we will be commandeering the select and using its onchange event handler to trigger an XMLHttpRequest() call to obtain the address information for the selected individual. The server will be returning this information as a string like this:

Bob Smith
123 School Street
Anytown, NY 12345We will take this return as a string and dump it into the pre element using innerHTML. Take a look at the code (line wraps marked » —Ed.):

var addressBook = {
myConn: false, // the XMLHttpRequest
body: false, // the body element
target: false, // the target container
loader: false, // the loader
init: function(controlId, sbmtBtnId, targetId){
/* init() takes three arguments:
* the id of the controller (select)
* the id of the submit button
* the id of the target container */
// test for methods & elements
if(!document.getElementById ||
!document.getElementsByTagName ||
!document.getElementById(controlId) ||
!document.getElementById(sbmtBtnId) ||
!document.getElementById(targetId)) return;
// set and test XHConn, quitting silently if it fails
addressBook.myConn = new XHConn();
if(!addressBook.myConn) return;
// get the body
addressBook.body = document.getElementsByTagName(’body’)[0];
// get the controller
var control = document.getElementById(controlId);
// get the submit button
var sbmtBtn = document.getElementById(sbmtBtnId);
// remove the submit button
sbmtBtn.parentNode.removeChild(sbmtBtn);
// get the target
addressBook.target = document.getElementById(targetId);
// add the onchange event to the controller,
addressBook.addEvent(control,
‘change’,
function(){
if(this.value != ”){
/* if there’s a value,
trigger getAddress */
addressBook.getAddress(this.value);
} else {
// otherwise empty the target
addressBook.target.innerHTML = ”;
}
});
},
getAddress: function(id){ // the Ajax call
// let’s let the user know something is happening (see below)
addressBook.buildLoader();
/* this is the function that is run
once the Ajax call completes */
var fnWhenDone = function(oXML) {
// get rid of the loader
addressBook.killLoader();
// insert the returned address information into the target
addressBook.target.innerHTML = oXML.responseText;
};
// use XHConn’s connect method
addressBook.myConn.connect(’index.php’, ‘POST’,
‘id=’+id, fnWhenDone);
},
buildLoader: function(){ // builds a loader
// create a new div
addressBook.loader = document.createElement(’div’);
// give it some style
addressBook.loader.style.position = ‘absolute’;
addressBook.loader.style.top = ‘50%’;
addressBook.loader.style.left = ‘50%’;
addressBook.loader.style.width = ‘300px’;
addressBook.loader.style.lineHeight = ‘100px’;
addressBook.loader.style.margin = ‘-50px 0 0 - 150px’;
addressBook.loader.style.textAlign = ‘center’;
addressBook.loader.style.border = ‘1px solid #870108′;
addressBook.loader.style.background = ‘#fff’;
// give it some text
addressBook.loader.appendChild( »
document.createTextNode( »
‘Loading Data, please wait\u2026′));
// append it to the body
addressBook.body.appendChild(addressBook.loader);
},
killLoader: function(){ // kills the loader
// remove the loader form the body
addressBook.body.removeChild(addressBook.loader);
},
addEvent: function(obj, type, fn){ // the add event function
if (obj.addEventListener) »
obj.addEventListener(type, fn, false);
else if (obj.attachEvent) {
obj[”e”+type+fn] = fn;
obj[type+fn] = function() {
obj[”e”+type+fn](window.event);
};
obj.attachEvent(”on”+type, obj[type+fn]);
}
}
};
/* run the init() method on page load, passing it
the required arguments */
addressBook.addEvent(window, ‘load’,
function(){
addressBook.init(’person’,
’submit’,
‘address’);
});See this script in action.

Example 2: Ajax with Nodes
Let’s alter the example, and instead of returning a string from the server, this time, make it XML:

Bob
Smith

123 School Street
Anytown
NY
12345

The XHTML page remains the same, but we need to make some minor adjustments to the JavaScript. To highlight the differences, I will touch on each change individually.

The first change, to the onchange event handler of the select, is pretty simple (line wraps marked » —Ed.):


addressBook.addEvent(addressBook.control,
‘change’,
function(){
if(this.value != ”){
addressBook.getAddress(this.value);
} else {
addressBook.target.removeChild( »
addressBook.target.firstChild);
}
});
…Instead of setting the content of the target to empty using innerHTML, the DOM is removing the node that is the target’s first child.

Next up is the getAddress() method (line wraps marked » —Ed.):


getAddress: function(id){
addressBook.buildLoader();
var fnWhenDone = function(oXML) {
addressBook.killLoader();
if(addressBook.target.hasChildNodes()){
addressBook.target.removeChild( »
addressBook.target.firstChild);
}
xml = oXML.responseXML;
var name = addressBook.getNodeValue(xml, ‘first’)+’ ‘+
addressBook.getNodeValue(xml, ‘last’);
var address = addressBook.getNodeValue(xml, ’street’);
var csz = addressBook.getNodeValue(xml, ‘city’)+’, ‘+
addressBook.getNodeValue(xml, ’state’)+’ ‘+
addressBook.getNodeValue(xml, ‘zip’);
var txt = document.createTextNode(name + “\ n” +
address + “\n” + csz);
addressBook.target.appendChild(txt);
};
addressBook.myConn.connect(’getAddress.php’, ‘POST’,
‘id=’ + id, fnWhenDone);
},
…As we are working with XML, we can use the responseXML property to get the return from the server as a node tree. Then we can traverse that tree, collecting the tidbits of information we need. In this example, we added a new method (getNodeValue()) that makes working with XML returns easier:


getNodeValue: function(tree, el){
return tree.getElementsByTagName(el)[0].firstChild.nodeValue;
},
…This method takes two arguments: the node tree (tree) and the element (el) whose content is wanted. It returns the nodeValue of the firstChild of the first el within tree or, in other words, the text value of the node requested from the node tree.

Once we have collected all of the requested contents from the XML, the text string is rebuilt and generated with the DOM before being appended to the target. The end result can be seen here.

You may be wondering, why do both examples do the exact same thing? It shows how you can work with two completely different backend systems and still get the results you want. In Ajax, as in many things, flexibility is important to get the job done.

Introducing Asynchronous Java Script and XML (Ajax) in ASP.NET

June 27, 2008

One of the most important challenges web application developers face is the requirement for a fast and responsive user interface. AJAX was primary designed and developed with the intent of providing a fast and responsive user interface to address these challenges. According to Enrich Peterson, “AJAX-enabled pages provide a slick, responsive user experience, making web-based applications function more like desktop-based ones”.

This article guides the reader through this new technology, its features, benefits and applicability in web application development. This is the first in the series of articles on Ajax (and more specifically ASP.NET AJAX). Although Ajax is independent of the technology with which it is implemented (you can implement Ajax enabled web applications using Java, Microsoft .NET or many other programming models), I will discuss implementation of Ajax in ASP.NET, how we can consume Web Services using AJAX, etc, in this series.

Why AJAX?

The primary advantages of using Ajax in web application development are as follows.

Ø Reduction of unnecessary web server hits, i.e., the round trips are minimized

Ø Rich, responsive user interface

Ø Real-time web page updates

Ø Language neutrality

Ø Faster web page renderings

Ø Less consumption of server’s resources (memory and processor load is reduced)

In the Ajax enabled web applications, requests are sent to the server only for the data that is needed. The entire web page is not submitted at one go.

Ajax makes use of XML, XSLT, XMLHttpRequest, JavaScript, HTML, and DHTML.

How does AJAX work?

Let us start by defining what AJAX is. AJAX, an acronym for Asynchronous JavaScript and XML, is a cross-platform technology that can be used to make your web pages fast, rich and responsive.

The key to the success of AJAX lies in the way it works. “Asynchronous” as it is called, implies that in the earlier days, the web applications used to be synchronous. This reminds me of the term “serial multi-tasking”, the type of multi-tasking the DOS Operating System used to support. A synchronous nature of execution implies that until and unless a request is complete in all respects, another cannot start. In other words, the requests have to be executed one after the other.

The AJAX engine runs within the context of the web browser using JavaScript and DOM technologies. In AJAX, the JavaScript that is loaded at the time when the web page loads is responsible for handling the basic tasks of data validation, changes to the data, etc; while the data transfer that happens from the user interface to the database and vice-versa, continues to happen in the background, i.e., it is independent of the other operation that we just mentioned about. This is what is known as “Asynchronous” mode of execution.

In an Ajax enabled web application, the runtime loads the Ajax engine instead of loading a webpage at the beginning. This engine is responsible for both rendering the data for the user interface and also communicating with the web server for transporting data back and forth. “The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server.”

Ajax is a mainly a mix of Javascript,Html, CSS, XML, DOM and the XMLHttpRequest Object. Ajax helps us to avoid reloading the web page as and when a specific portion of the web page changes due to user inter actions. Using Ajax, you can dynamically retrieve data from the application running in the context of the web server whenever a user interaction happens using the XMLHTTPRequest object. But, what is this XMLHTTPRequest object? Today’s browsers contain the XMLHttpRequest object that can be used to create a GET or POST request asynchronously. It also helps us to register a callback method that is invoked when the resposne for that request returns to the client side browser. This response can in turn be either in plain text or in XML format. In the former case, we can simply display the response in the web browser; in the later, you require parsing the XML prior to displaying in the browser. Note that the XMLHttpRequest Object is one of the major components of the Ajax framework and facilitates asynchronous processing and also supports events.

AJAX and ASP.NET

Microsoft introduced support for AJAX in ASP.NET in the form of a separate add-on called ASP.NET 2.0 AJAX Extensions, an extension of ASP.NET that is totally integrated with the server-based services and helps you to design and implement Ajax enabled web applications using ASP.NET technology. It actually is comprised of a set of technologies that enable AJAX support in the ASP.NET environment. According to MSDN, “ASP.NET AJAX is a set of technologies to add AJAX (Asynchronous JavaScript and XML) support to ASP.NET. It consists of a client-side script framework, server controls, and more”. “Although AJAX is essentially a client-side technique, most of its real-world deployments call for server-side processing.”

The ASP.NET 2.0 framework incorporates the client script libraries of the ASP.NET Ajax framework. Note that ASP.NET AJAX is an extension of the ASP.NET server-based development framework. You can use ASP.NET AJAX to build web applications with rich user interface and improved response times. “The framework includes two distinct yet not mutually exclusive API’s: client and server, which enable the developers to accomplish AJAX functionalities using direct client-side programming, traditional server-side programming, or any combination of both”.

Available ASP.NET Ajax Frameworks

These are several of Ajax frameworks for ASP.NET that you can choose from. The following are some of the best Ajax frameworks.

Ajax.NET Professional

ASP.NET AJAX from Microsoft

Ajax.NET

MajicAjax.NET

The ASP.NET AJAX Control Toolkit

The ASP.NET AJAX Control Toolkit from Microsoft is a community project that comprises of a SDK and code samples. According to Microsoft, “The ASP.NET AJAX Control Toolkit provides a set of sample controls and extenders that makes it a snap to spice up your web site with rich functionality”.

You can download the Ajax Control Toolkit from the following link:

http://www.codeplex.com/AtlasControlToolkit/Release/ProjectReleases.aspx

Suggested Readings

http://www.ajaxtoday.com/ArticleDetail/tabid/62/ArticleID/45/Default.aspx

http://www.developerfusion.co.uk/show/4704/

http://aspnet.4guysfromrolla.com/articles/062106-1.aspx

http://www.codeproject.com/Ajax/IntroAjaxASPNET.asp

AJAX Downloads and Resources

You can download AJAX from the following link. This is the official link for ASP.NET AJAX resources. http://ajax.asp.net/downloads/

Conclusion

Asynchronous JavaScript and XML, or AJAX is a technology that can be used to send and receive data (usually in XML format) from a server-side application using

Javascript. AJAX has introduced radical changes in how web applications are developed these days. You can use ASP.NET AJAX to enrich the user interface of your web applications seamlessly and ensure that the user interface is fast and responsive with less resource overheads involved for rendering of data from the web server to the web clients. The forthcoming articles in this series of articles on Ajax would discuss more and more on Ajax and how we can build and implement Ajax in ASP.NET applications. So, stay tuned!

Getting started with AJAX using PHP : Tutorial

June 27, 2008

AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms.

In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is not a programming language, so you don’t have to learn any new technology. AJAX can be implemented by using existing standards (JavaScript and XML) in a different way.

If we are using PHP or any server side technology and need to extract data from storage on a server (eg a database or a file), we will have to make an HTTP request (either POST or GET) to get the data. Once the data is received the the web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from server in background and then display it on the page without a reload. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object (XML over HTTP). With an HTTP request, a web page can make a request to, and get a response from a web server without reloading the page.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. But the creation of XMLHttpRequest object is different in Internet Explorer than the other browsers. I will discuss this later. To use AJAX to request a data from the server we need to do the following.

1. Create an XMLHttpRequest object.
2. Then using this object, request data from the server.
3. JavaScript will then monitor for the changing of state of the request.
4. If the response is successful, then the content from the data store requested will be returned as response (response can be in the form of a String or XML).
5. Use the response in your web page.

1. Create an XMLHttpRequest object

JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object. The following codes creates an XMLHttpRequest for all browsers:

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5
req = new ActiveXObject(”Microsoft.XMLHTTP”);
} else if(window.ActiveXObject){
//For IE 6+
req = new ActiveXObject(”Msxml2.XMLHTTP”);
}
else{
//Error for an old browser
alert(’Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject(”Microsoft.XMLHTTP”) and for IE 6.0+ use new ActiveXObject(”Msxml2.XMLHTTP”). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.

var req;
try
{
// Firefox, Opera, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
catch (e)
{
alert(’Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
}
}

In JavaScript, if statements within a try section fail, then the execution resumes from the corresponding catch block. Here first we are trying to get create a XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject(”Msxml2.XMLHTTP”), and if it fails also we will try ActiveXObject(”Microsoft.XMLHTTP”). If all these fail, then we will alert the user that his/her browser does not support AJAX.

2. Request for a web page

After creating the XMLHttpRequest we now need to send the web request using the open method. We also need to specify the HttpRequest method, GET or POST. Use the following code to send the request.

req.open(“GET”,”somedata.php”);
req.send(null);

Here, req is the XMLHttpRequest object. It will request to the server for somedata.php using GET method. The open function also has a third parameter, an optional boolean parameter. You should set that to true :

req.open(“GET”,”somedata.php”,true);
req.send(null);

Both of the above is correct.

3. Monitor for the response of the request

You will need to monitor for the state of the request. For doing this you can assign a function to req.onreadystatechange (Here, req is the XMLHttpRequest object), like below.

req.onreadystatechange=function()
{
if(req.readyState==4 && req.status == 200)
{
var resp = req.responseText;
}
}

Or like this,

req.onreadystatechange = handleResponse;

function handleResponse(){
if(req.readyState == 4 && req.status == 200){
//returned text from the PHP script
var response = req.responseText;
}
}

The readyState property holds the status of the server’s response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State Description
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

And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.

4. Get the response

The response will be as string or as XML. The data sent back from the server can be retrieved with the responseText property as string. Use responseXML for getting the response as XML.

5. Use the response on your web page

You can use the response you got from the XMLHttpRequest in your web page/application. You can either set a value of a text field or use the returned HTML from the web request as innerHTML for a

tag or tag (See below for the implementation of this)

Using AJAX with PHP

I usually place all the AJAX related functions in one JavaScript (ajax.js), and later add the JavaScript in my PHP pages. My ajax.js looks like below.

function createRequestObject(){

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(”Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(’Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}

function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(”ajax_res”).innerHTML = response;
}
}
}

Now I add a tag in my PHP pages like following to access the JavaScript functions.

Then I create a function called sendReq() as shown above for preparing the URL to the PHP page to get some data from the database. If you look into the ajax.js, you will see that I’m assigning the output of the PHP page to a

tags innerHTML. My div tag has the id=’ajax_res’.

After calling the sendReq function with a value of ‘success’, it will connect to the server for sending a request to the URL get_lcm.php?status=success, then get the data from the database using the value ‘success’, and set the innerHTML attribute of the div tag whose id is ‘ajax_res’ according to the response. Initially my div tag shows an image, but after AJAX responds successfully this image will be replaced with the response. You can also get the response as the value of an input text.

My get_lcm.php looks like this.

<?php
include_once(”create_table.php”);

if(!empty($status)){
echo “Search Result for Status: “.$status.”

“;

$ct = new createtable(”select * from lcm where state=$status”);

$ct->table_viewer();
}
?>

I used one of my PHP classes ‘create_table.php’ for creating a table from SQL queries. ‘create_table.php’ has a function, table_viewer(), to print the SQL output as a HTML table. I will discuss about this class and some other data abstraction classes I used in some later articles, if necessary.

I had the following HTML code for calling the AJAX function using the sendReq() as described earlier.

ACTIVE

If a user clicks the above hyperlink, then the JavaScript function sendReq is invoked using the value of status equal to 1. After that the webpage with URL get_lcm.php?status=1 will be invoked. This PHP will get the information from database and shows the result as table. This result will then be displayed within the

tag.

Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development is you place all your AJAX related code in a single JavaScript file and reference it from anywhere you need AJAX.

There is another way of getting the same result from PHP without using the XMLHttpRequest object. But I personally do not like the concept, because it is missing one of the main ingredients of Asynchronous JavaScript And XML (AJAX), XML. This concept is good for the old browsers with no supports for XMLHttpRequest object, but as all the newer versions are supporting XMLHttpRequest object you can use AJAX for the common browsers.

So - how do you find out more about Ajax and how it interacts with the system?

May 13, 2008

Before I found this weblog I though Ajax was something we used to clean the bathroom. (haha) Now I understand some of the potential weakness and strength that has to do with the scripting. I would like to know how others managed to find tutorials that were appropriate and learner friendly for the run of the mill computer junkie?

Next Page »

Bottom