Sunday, 30 December 2012

AJAX



AJAX
AJAX, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications.
AJAX meant to increase the web page's interactivity, speed, and usability.
If you know Javascript, HTML, CSS and XML then you need to spend just one hour to startwith AJAX.
·         AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
·         Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and JavaScript for dynamic content display.
·         Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
·         With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
·         XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.
·         AJAX is a web browser technology independent of web server software.
·         A user can continue to use the application while the client program requests information from the server in the background
·         Intuitive and natural user interaction. No clicking required only Mouse movement is a sufficient event trigger.
·         Data-driven as opposed to page-driven
Technologies Used in AJAX

JavaScript

·         Loosely typed scripting language
·         JavaScript function is called when an event in a page occurs
·         Glue for the whole AJAX operation

DOM

·         API for accessing and manipulating structured documents
·         Represents the structure of XML and HTML documents

CSS

·         Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript

XMLHttpRequest

·         JavaScript object that performs asynchrous interaction with the server
AJAX APPLICATIONS

Google Maps

A user can drag the entire map by using the mouse instead of clicking on a button or something
·         http://maps.google.com/

Google Suggest

As you type, Google will offer suggestions. Use the arrow keys to navigate the results

Gmail

Gmail is a new kind of webmail, built on the idea that email can be more intuitive, efficient and useful
·         http://gmail.com/

Yahoo Maps (new)

Now it's even easier and more fun to get where you're going!
·         http://maps.yahoo.com/

Steps of AJAX Operation

1.      A client event occurs
2.      An XMLHttpRequest object is created
3.      The XMLHttpRequest object is configured
4.      The XMLHttpRequest object makes an asynchronous request to the Webserver.
5.      Webserver returns the result containing XML document.
6.      The XMLHttpRequest object calls the callback() function and processes the result.
7.      The HTML DOM is updated

1. A client event occurs

·         A JavaScript function is called as the result of an event
·         Example: validateUserId() JavaScript function is mapped as a event handler to a onkeyup event on input form field whose id is set to "userid"
·         <input type="text" size="20" id="userid" name="id" onkeyup="validateUserId();">

2. The XMLHttpRequest object is created

var ajaxRequest;  // The variable that makes Ajax possible!
function ajaxFunction(){
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
}

3. The XMLHttpRequest object is Configured

In this step we will write a function which will be triggered by the client event and a callback function processRequest() will be registered
function validateUserId() {
   ajaxFunction();
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatechange = processRequest;
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
}

4. Making Asynchornous Request to the Webserver

Source code is available in the above piece of code. Code written in blue color is responsible to make a request to the web server. This is all being done using XMLHttpRequest object ajaxRequest
function validateUserId() {
   ajaxFunction();
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatechange = processRequest;
 
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
 
}
Assume if you enter mohammad in userid box then in the above request URL is set to validate?id=mohammad

5. Webserver returns the result containing XML document

You can implement your server side script in any language. But logic should be as follows
·         Get a request from the client
·         Parse the input from the client
·         Do required processing.
·         Send the output to the client.

6. Callback function processRequest() is called

The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will recieve the result from the server and will do required processing. As in the following example it sets a variable message on true or false based on retruned value from the Webserver.
function processRequest() {
   if (req.readyState == 4) {
      if (req.status == 200) {
         var message = ...;
...
}

7. The HTML DOM is updated

This is the final step and in this step your HTML page will be updated. It happens in the following way
<li
JavaScript technology gets a reference to any element in a page using DOM API
·         The recommended way to gain a reference to an element is to call.
</li


XMLHttpRequest

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.
XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.
The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.
You already have seen couple of examples on how to create a XMLHttpRequest object.
Below is listed some of the methods and properties you have to become familiar with.

XMLHttpRequest Methods

·         abort()
Cancels the current request.
·         getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
·         getResponseHeader( headerName )
Returns the value of the specified HTTP header.
·         open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible

The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
·         send( content )
Sends the request.
·         setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties

·         onreadystatechange
An event handler for an event that fires at every state change.
·         readyState
The readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:
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 completed
readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
·         responseText
Returns the response as a string.
·         responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
·         status
Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
·         statusText
Returns the status as a string (e.g. "Not Found" or "OK").

AJAX Security

Ajax Security : Server Side

·         AJAX-based Web applications use the same serverside security schemes of regular Web applications
·         You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programatic)
·         AJAX-based Web applications are subject to the same security threats as regular Web applications

Ajax Security : Client Side

·         JavaScript code is visible to a user/hacker. Hacker can use the JavaScript code for inferring server side weaknesses
·         JavaScript code is downloaded from the server and executed ("eval") at the client and can compromise the client by mal-intended code
·         Downloaded JavaScript code is constrained by sand-box security model and can be relaxed for signed JavaScript

Current Issues with AJAX

AJAX is growing very fast and that is the reason that it contains many issues with it. We hope with the passes of time they will be resolved ab AJAX will be ideal for web applications. We are listing down few issues which AJAX has as a challenge.
Complexity is increased
·         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
·         Page developers must have JavaScript technology skills
AJAX-based applications can be difficult to debug, test, and maintain
·         JavaScript is hard to test - automatic testing is hard
·         Weak modularity in JavaScript
·         Lack of design patterns or best practice guidelines yet
Toolkits/Frameworks are not mature yet
·         Most of them are in beta phase
No standardization of the XMLHttpRequest yet
·         Future version of IE will address this
No support of XMLHttpRequest in old browsers
·         Iframe will help
JavaScript technology dependency & incompatibility
·         Must be enabled for applications to function
·         Still some browser incompatibilities
JavaScript code is visible to a hacker
·         Poorly designed JavaScript code can invite security problem


AJAX Introduction
AJAX is about updating parts of a web page, without reloading the whole page

What is AJAX?

AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works



AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:
  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)
lamp  AJAX applications are browser- and platform-independent!

AJAX Example

The AJAX application above contains one div section and one button.
The div section will be used to display information returned from a server. The button calls a function named loadXMLDoc(), if it is clicked:
<html>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>
Next, add a <script> tag to the page's head section. The script section contains the loadXMLDoc() function:
<head>
<script type="text/javascript">
function loadXMLDoc()
{
.... AJAX script goes here ...
}
</script>
</head>

 

 

AJAX - Create an XMLHttpRequest Object

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:

Example

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");
  }

AJAX - Send a Request To a Server



The XMLHttpRequest object is used to exchange data with a server.

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","ajax_info.txt",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.

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

GET Requests

A simple GET request:

Example

xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
In the example above, you may get a cached result.
To avoid this, add a unique ID to the URL:

Example

xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
If you want to send information with the GET method, add the information to the URL:

Example

xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();


POST Requests

A simple POST request:

Example

xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:

Example

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

Method
Description
setRequestHeader(header,value)
Adds HTTP headers to the request.

header: specifies the header name
value: specifies the header value


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","ajax_test.asp",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","ajax_test.asp",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:

Example

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
You will learn more about onreadystatechange in a later chapter.

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:

Example

xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

 AJAX - Server Response


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:

Example

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


The responseXML Property

If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property:

Example

Request the file cd_catalog.xml and parse the response:
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;

 



No comments:

Post a Comment