Thursday, April 29, 2010

AJAX


AJAX

 

Defining Ajax

Ajax isn't a technology. It's really several technologies, each flourishing in its own right, coming together in powerful new ways.

AJAX is based on the following web standards:

·    JavaScript

·      XML

·      HTML

·      CSS

 

The classic web application model works like this: Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing — retrieving data, crunching numbers, talking to various legacy systems — and then returns an HTML page to the client.

 

How Ajax is Different

An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame.

 

 

Q. Why did you feel the need to give this a name?

A. I needed something shorter than "Asynchronous JavaScript+CSS+DOM+XMLHttpRequest" to use when discussing this approach with clients.

Q. Is Ajax a technology platform or is it an architectural style?

A. It's both. Ajax is a set of technologies being used together in a particular way.

 

 

AJAX have some challenges as well

 

1.                          Complexity: Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic to generate the XML content needed by the client HTML pages. HTML page developers need to have a basic understanding of JavaScript technology to create new Ajax functionality.

2.                          Standardization of the XMLHttpRequest object: The XMLHttpRequest object is not yet part of the JavaScript technology specification, which means that the behavior may vary depending on the client.

3.                          JavaScript technology implementations: Ajax interactions depend heavily on JavaScript technology, which has subtle differences depending on the client

4.                          Debugging: Ajax applications are also difficult to debug because the processing logic is embedded both in the client and on the server.

5.                          Securing resources and protecting your data: You can view client-side JavaScript technology simply by selecting View Source from an Ajax-enabled HTML page. A poorly designed Ajax-based application could open itself up to hackers or plagiarism.

 

Using Ajax requires that you use the latest browser versions that support the XMLHttpRequest object needed for Ajax interactions.

 

Using Ajax also requires a great deal of client-side JavaScript technology and CSS.

 

The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.

 

AJAX was made popular in 2005 by Google (with Google Suggest).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

AJAX PROGRAMMNG

 

 

It has some stages.

 

1.      Check Browser Supporting or Not

 

function GetXmlHttpObject()

{

var xmlHttp=null;

try

  {

  // Firefox, Opera 8.0+, Safari

  xmlHttp=new XMLHttpRequest();

  }

catch (e)

  {

  // Internet Explorer

  try

    {

    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

    }

  catch (e)

    {

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

    }

  }

        mlHttp=GetXmlHttpObject();

        if (xmlHttp==null)

        {

          alert ("Your browser does not support AJAX!");

          Return;

        }

 

2.      Analysis of Processing states Values  (ReadyState Property)

 

 

if (httpRequest.readyState == 4) {

    // everything is good, the response is received

} else {

// still not ready

}

 

a.   0: Uninitialized

b.   1: Loading (Open)

c.   2: Loaded (Sent)

d.   3: Interactive (Receiving)

e.   4: Complete (Loaded)

 

3.      The next thing to check is the status code of the HTTP server response.

 

if (httpRequest.status == 200) {

    // perfect!

} else {

    // there was a problem with the request,

    // for example the response may be a 404 (Not Found)

    // or 500 (Internal Server Error) response codes

}

 

if (httpRequest.readyState == 4) {

            if (httpRequest.status == 200) {

                alert(httpRequest.responseText);

            } else {

                alert('There was a problem with the request.');

            }

        }

 

    }

 

 

4.     You need to decide what you want to do after you receive the server response to your request.

 

httpRequest.onreadystatechange = function(){

    // do the thing

};

 

5.     After you've declared what will happen as soon as you receive the response, you need to actually make the request. You need to call the open() and send() methods of the HTTP request class.

 

AJAX - Sending a Request to the Server To send off a request to the server, we use the open() method and the send() method.

 

httpRequest.open('GET', 'http://www.example.org/some.file',true);

httpRequest.send(null);

 

You have two options to access that data (the data the server has sent to you):

§ httpRequest.responseText – will return the server response as a string of text

§ httpRequest.responseXML – will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

 

 

1        The first parameter of the call to open() is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard;

2        The second parameter is the URL of the page you're requesting. As a security feature, you cannot call pages on 3rd-party domains.

3        The third parameter sets whether the request is asynchronous.

4        The parameter to the send () method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:

name=value&anothername=othervalue&so=on

Note that if you want to POST data, you have to change the MIME type of the request using the following line:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Otherwise, the server will discard the POSTed data.

 

 

Client .htm

 

 

<html>

<head>

<script src="selectcustomer_xml.js"></script>

</head>

<body>

<form action="">

Select a Customer:

<select name="customers" onchange="showCustomer(this.value)">

<option value="ALFKI">Alfreds Futterkiste</option>

<option value="NORTS ">North/South</option>

<option value="WOLZA">Wolski Zajazd</option>

</select>

</form>

<b><span id="companyname"></span></b><br />

<span id="contactname"></span><br />

<span id="address"></span>

<span id="city"></span><br/>

<span id="country"></span>

</body>

</html>

 

 

This is the JavaScript code stored in the file "selectcustomer_xml.js":

 

 

var xmlHttp

function showCustomer(str)

{

xmlHttp=GetXmlHttpObject();

if (xmlHttp==null)

  {

  alert ("Your browser does not support AJAX!");

  return;

  }

var url="getcustomer_xml.asp";

url=url+"?q="+str;

url=url+"&sid="+Math.random();

xmlHttp.onreadystatechange=stateChanged;

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

xmlHttp.send(null);

}

function stateChanged()

{

if (xmlHttp.readyState==4)

{

var xmlDoc=xmlHttp.responseXML.documentElement;

document.getElementById("companyname").innerHTML=

xmlDoc.getElementsByTagName("compname")[0].childNodes[0].nodeValue;

document.getElementById("contactname").innerHTML=

xmlDoc.getElementsByTagName("contname")[0].childNodes[0].nodeValue;

document.getElementById("address").innerHTML=

xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;

document.getElementById("city").innerHTML=

xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;

document.getElementById("country").innerHTML=

xmlDoc.getElementsByTagName("country")[0].childNodes[0].nodeValue;

}

}

 

function GetXmlHttpObject()

{

var xmlHttp=null;

try

  {

  // Firefox, Opera 8.0+, Safari

  xmlHttp=new XMLHttpRequest();

  }

catch (e)

  {

  // Internet Explorer

  try

    {

    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

    }

  catch (e)

    {

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

    }

  }

return xmlHttp;

}

 

The server page called by the JavaScript, is a simple ASP file called "getcustomer_xml.asp".

 

<%

response.expires=-1

response.contenttype="text/xml"

sql="SELECT * FROM CUSTOMERS "

sql=sql & " WHERE CUSTOMERID='" & request.querystring("q") & "'"

 

on error resume next

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

conn.Open(Server.Mappath("/db/northwind.mdb"))

set rs=Server.CreateObject("ADODB.recordset")

rs.Open sql, conn

if err <> 0 then

response.write(err.description)

set rs=nothing

set conn=nothing

else

response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")

response.write("<company>")

response.write("<compname>" &rs.fields("companyname")& "</compname>")

response.write("<contname>" &rs.fields("contactname")& "</contname>")

response.write("<address>" &rs.fields("address")& "</address>")

response.write("<city>" &rs.fields("city")& "</city>")

response.write("<country>" &rs.fields("country")& "</country>")

response.write("</company>")

end if

on error goto 0

%>

 

 

No comments:

Post a Comment