Infolink

 

Search This Blog

Aug 15, 2012

AJAX

Ajax stands for Asynchronous JavaScript and XML. Ajax isn’t a technology; it mixes well-known programming techniques in an uncommon way to enable web developers to build Internet applications with much more appealing user interfaces. When using desktop applications, we expect the results of our work to be made available immediately and without us having to wait for the whole screen to be redrawn by the program. While using a spreadsheet such as Excel, for instance, we expect the changes we make in one cell to propagate immediately through the neighboring cells while we continue to type, scroll the page, or use the mouse.

Unfortunately, this sort of interaction has rarely been available to users of web-based applications. Much more common is the experience of entering data into form fields, clicking on a button or link, and then sitting back while the page slowly reloads to exhibit the results of the request. In addition, we often find that the majority of the reloaded page consists of elements that are identical to those of the previous page and that have therefore been reloaded unnecessarily such as background images, logos, and menus.

Ajax gives a solution to this problem. By working as an extra layer between the browser and the web server, Ajax handles server communications in the background, submitting server requests and processing the returned data. The results may then be integrated into the page being viewed, without that page needing to be refreshed or a new one loaded.

In Ajax applications, such server requests are not necessarily synchronized with user actions such as clicking on buttons or links. A well-written Ajax application may already have asked of the server, and received, the data required by the user perhaps before the user even knew he wanted it. This is the meaning of the asynchronous part of the Ajax acronym.

The parts of an Ajax application that happen "under the hood" of the browser, such as sending server queries and dealing with the returned data, are written in JavaScript, and XML is a means of coding and transferring formatted information used by Ajax to efficiently transfer data between server and client.

What makes AJAX Useful?

AJAX development is a big step towards web development instead of having to send everything to the server in a single, huge mass, then wait for the server to send back a new page for rendering, web developers can communicate with the server in smaller chunks, and selectively update specific areas of the page based on the server’s responses to those requests. This is where the word asynchronous in the AJAX originated.

It’s is easy to understand the idea of an asynchronous system by considering its opposite—a synchronous system. In a synchronous system, everything occurs in order. If a car race was a synchronous system, it would be a very dull affair. The car that started first on the grid would be the first across the finish line, followed by the car that started second, and so on. There would be no overtaking and if a car broke down, the traffic behind would be forced to stop and wait while the mechanics made their repairs. Traditional web applications use a synchronous system you must wait for the server to send you the first page of a system before you can request the second page.

Traditional Web Application Vs Ajax Web Application




So from above two figures we can easily make out the difference between Traditional web application and AJAX web application. AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications.

With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.The AJAX technique makes Internet applications smaller, faster and more user-friendly.

XMLHttpReqeust

To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.
With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.

With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded.

The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari

Creating XMLHTTPRequest Object

You cannot make use of the XMLHTTPRequest until you have created an instance of it.

Microsoft first introduced the XMLHTTPRequest object, implementing it in Internet Explorer 5 as an ActiveX object.

The following line creates an XMLHTTPRequest object called request
 
               var request = new XMLHTTPRequest();
 
Here we have declared a variable request and assigned to it the value returned 
from the statement new XMLHTTPRequest(), which is invoking the constructor 
method for the XMLHTTPRequest object.
 
To achieve the equivalent result in Microsoft Internet Explorer, you need to 
create an ActiveX object.
 
Here's an example
 
               var request = new ActiveXObject("Microsoft.XMLHTTP");
 
This assigns the name request to the new object.
 
Some versions of Internet Explorer have a different version of MSXML, 
the Microsoft XML parser, installed; in those cases you need to use the following
instruction
 
               var request = new ActiveXObject("Msxml2.XMLHTTP");
 
For cross Browser detection, this is the following code
function ajaxFunction()
{
               var xmlhttp;
               if (window.XMLHttpRequest)
                {
               // code for IE7+, Firefox, Chrome, Opera, Safari
               xmlhttp=new XMLHttpRequest();
                }
               else if (window.ActiveXObject)
                {
                // code for IE6, IE5
               xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
               else
                 {
               alert("Your browser does not support XMLHTTP!");
                }
}
 
In above example create a variable named xmlhttp to hold the XMLHttpRequest 
object,Try to create the XMLHttpRequest object with 
xmlhttp=new XMLHttpRequest(). If that fails, try xmlhttp=
new ActiveXObject("Microsoft.XMLHTTP"). This is for IE6 and IE5. If that fails too, 
the user has a very outdated browser, and will get an alert stating that the
browser doesn't support XMLHTTP.
 
Note: The code above can be used every time you need to create an XMLHttpRequest object.
 
XMLHttpRequest Communicated with Server
Before sending data off to a server, we will look at some important properties and methods of the XMLHttpRequest object.

XMLHttpRequest Properties

The onreadystatechange property

After a request to a server, we need a function to receive the data returned from the server.
The onreadystatechange property stores the function that will process the response from a server. The function is stored in the property to be called automatically.
onreadystatechange property - you can create a function  (sometimes called an anonymous function because it doesn’t have a name). To create a function , just use the function statement and define the body of this new function in curly braces.
This new, anonymous function will be called when the XMLHttpRequest object undergoes some change, as when it downloads data. We need to watch two properties of this object here - the readyState property and the status property.
The following code sets the onreadystatechange property and stores an empty function inside it
            xmlhttp.onreadystatechange=function()
{
// We are going to write some code here
}

 

The readyState property

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

Possible values for the readyState property

State
Description
0
The request is not initialized () The object has been created but the open() method hasn't been called. )
1
The request has been set up (The open() method has been called but the request hasn't been sent. )
2
The request has been sent
3
The request is in process (A partial response has been received)
4
The request is complete (All data has been received and the connection has been closed. )

Add an If statement to the onreadystatechange function to test if the response is complete (means that now we can get our data)
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
  {
  // Get data from the server's response
  }
}

When a server request is first made, the value of readyState is set to zero, meaning uninitialized. As the server request progresses, data begins to be loaded by the server into the XMLHTTPRequest object, and the value of the readyState property changes accordingly, moving to 1 and then 2. An object readyState value of 3, interactive, indicates that the object is sufficiently progressed so that certain interactivity with it is possible, though the process is not yet fully complete. When the server request has completed fully and the object is available for further processing, the value of readyState changes finally to 4. In most practical cases, you should look for the readyState property to achieve a value of 4, at which point you can be assured that the server has finished its task and the XMLHTTPRequest object is ready for use.

Status property:

The status property holds the status of the download itself. (This is the standard HTTP status code that the browser got for the URL you supplied.) Here are some of the possible values the status property can hold (note that a value of 200 means everything is just fine)
  • 200 -    OK - The request succeeded.
·         204 -    No Content - The document contains no data.
·         401 -    Unauthorized - The request needs user authentication.
  • 403 -    Forbidden - The server has refused to fulfill the request
·         404 -    Not Found - The requested resource does not exist on the server.
·         408 -    Request Timeout - The client failed to send a request in the time allowed by the server.
·         500 -    Internal Server Error - Due to a malfunctioning script, server configuration error or similar.

Example

xmlhttp.onreadystatechange=function()                     // anonymous function will create
{
if(xmlhttp.readyState==4 && xmlhttp.status == 200)
  {
  // Get data from the server's response
  }
}

The responseText property

The data sent back from a server can be retrieved with the responseText property. Now, we want to set the value of the "Time" input field equal to responseText.

xmlhttp.onreadystatechange=function()

{

if(xmlhttp.readyState==4)

  {

  document.myForm.time.value=xmlhttp.responseText;

  }           

XMLHttpRequest Methods

To send off a request to the server, we can use the open() and send() methods.

Open()

The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously.

The open() method prepares the XMLHTTPRequest object to communicate with the server. After you have created an XMLHttp object, you are ready to start making HTTP requests from JavaScript. The first step is to call the open() method, which initializes the object. The syntax is as under
Syntax
open(“method”, “URL”, [async, username, password])

We need to supply at least the two mandatory arguments to this method. First, specify which HTTP method you intend to use, usually GET or POST as a string value. Next, the destination URL of the request is included as the second argument. If making a GET request, this URL needs to be suitably encoded with any parameters and their values as part of the URL. For security reasons, the XMLHTTPRequest object is allowed to communicate only with URLs within its own domain. An attempt to connect to a remote domain results in a "permission denied" error message. Optionally you may include a third argument to the send request, a boolean value to declare whether the request is being sent in asynchronous mode. If async is set to false, the request is sent synchronously, and JavaScript waits for a response from the server before continuing code execution. That means if the response takes a long time, the user cannot interact with the browser until the response has completed. The default value is true. When set to true, the request is sent asynchronously, and JavaScript code execution continues without waiting for the response, we must use an event handler to watch for the response to the request.

send()

After creating XMLHTTPRequest using the open() method, you can send the request using the send() method. One argument is accepted by the send() function. The syntax is as under

Syntax
send(content)

If your request is a GET request, the request information will be encoded into the destination URL, and you can then simply invoke the send() method using the argument null
objectname.send(null);
If your request is POST request, the content of the request (suitably encoded) will be passed as the argument.
objectname.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
objectname.send(var1=value1&var2=value2);

In this case we use the setRequestHeader() method to indicate what type of content we are including. The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be
xmlhttp.open("GET","time.php",true);
xmlhttp.send(null);

Now let’s see some example of AJAX


AJAX with HTML

ajaxdemo.html

<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
                        http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}
function replace()
{
  http.open("GET", "test.txt", true);
  http.onreadystatechange=function()
 {
    if(http.readyState == 4) {
      document.getElementById('changed').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>

<p><a href="javascript:replace()">Replace Text</a></p>

<div id="changed">
            Hello, world!
</div>

test.txt

This is the content of test.txt

Output




 
  
In above program AJAX is used HTML, when user click on Replace Text link it will call replace function, in replace() function open() method is used to open file test.txt and send method will send request to server, request to server will send by using send() method only, if we have used only open() method than it will not send request to open it will just prepare a data to send to server, now when server response to that request send it will call the anonyms function, the XMLHttpRequest object undergoes some change, and when it will downloads data readystate property value will set to 4, it will print the content of text file in place of Hello World without reloading the page.

AJAX  with PHP

Example 

ajaxhtml.html

<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer")
{
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}
function validate(user)
 {
 http.open("GET", "validate.php?name=" + user, true);
            http.onreadystatechange=function()
{
            if(http.readyState == 4) {
                        document.getElementById('data').innerHTML = http.responseText;
             }
  }
  http.send(null);
}
</script>
<h1>Please choose your username :</h1>
<form>
  <input type="text" onkeyup="validate(this.value)" />
  <div id=data></div>
</form>

validate.php

<?php
function validate($name)
{
  if($name == '') {
    return '';
  }
 if(strlen($name) < 3) {
             return "<span id=\"spantag\">Username too short</span>\n";
            }
            switch($name)
{
            case 'tom':
            case 'jerry':
            case 'john':
             case 'snohit':
            return "<span id=\"spantag\">Username already taken</span>\n";
             }
return "<span id=\"spantag\">Username ok! </span>\n";
}
echo validate(trim($_REQUEST['name']));
?>

Output




Figure 5.6 Example of AJAX and PHP
In above example user will enter the name in text box, when user will typed message will print too short, Username OK , or Username already taken. Depends on user enter the name, if name is less than 2 character it will print Username too short, if user name is already in switch case loop like tom, jerry and john it will print Username already taken.

in above program ajaxhtml.html file will send request validate.php?name=user to server using xmlHttpRequest object, server will call file validate.php and check the name, if number of character is 2 it will print Username too short, else it will check the name entered in switch if not found then print Username OK.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...