Advertise

Monday 23 September 2013

Learn Ajax Programming From A to Z | Complete Ajax Programming Reference.

Table of Contents:

>> What's AJAX?

Step 1 – How to make an HTTP request

Step 2 – Handling the server response

Step 3 – A Simple Example

Step 4 – Working with the XML response

Step 5 – Working with data


[Image: UI5lj.png]

AJAX = Asynchronous JavaScript and XML.
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
it is the use of the XMLHttpRequest object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including JSON, 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 lets you update portions of a page based upon user events.

The two features in question are that you can:

  • Make requests to the server without reloading the page.
  • Receive and work with data from the server

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


In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called XMLHTTP. Then Mozilla, Safari, and other browsers followed, implementing an XMLHttpRequest class that supports the methods and properties of Microsoft's original ActiveX object.

Syntax :-

Code:
variable=new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:

Code:
variable=new ActiveXObject("Microsoft.XMLHTTP");


Step 1 – How to make an HTTP request


As a result, in order to create a cross-browser instance (object) of the required class, you can do the following:
Example :-

Code:
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

Imporant :- This is Simply version to make you understand how his works, but to code in your real life web prjects, there are few more things to ammend, Keep on Reading till End to understand better and to know how to use in real life scenario.

Next, you need to decide what you want to do after you receive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function will handle processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function that should be called when the state of the request changes, like this:

PHP Code:
httpRequest.onreadystatechange nameOfTheFunction

Note that there are no parentheses after the function name and no parameters passed, because you're simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous functions") and define the actions that will process the response right away, like this:

PHP Code:
httpRequest.onreadystatechange = function(){
    
// process the server response}; 

Next, 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, like below:

Send a Request To a Server


PHP Code:
httpRequest.open('GET''http://www.worldofhacker.com/some.file'true);httpRequest.send(null); 

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

  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; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the W3C specs.
  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. Be sure to use the exact domain name on all of your pages or you will get a "permission denied" error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with http://www.domain.tld. If you really need to send a request to another domain, see HTTP access control.
  3. The optional third parameter sets whether the request is asynchronous. If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.


The parameter to the send() method can be any data you want to send to the server if POST-ing the request. Form data should be sent in a format that the server can parse easily. This can be as a query string, like:

PHP Code:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on" 

in several other formats, including JSON, SOAP, etc.

Note that if you want to POST data, you may have to set the MIME type of the request. For example, use the following line before calling send() for form data sent as a query string:

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


Understanding 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


In the example below, you may get a cached result, So adding an Unique Identifier is always Good Idea.[See below this code for that]

PHP Code:
httpRequest.open("GET","demo_get.php",true);httpRequest.send(); 

Adding an Unique Identifier with Math.random() Function. Google Search Results for: Math.random()

PHP Code:
httpRequest.open("GET","demo_get.php?t=" Math.random(),true);httpRequest.send(); 

For a Live demo of above code, Go and Open w3schools.com and open any "Try Yourself" page and see the view source of Try yourself page at approx line 20 orsubmitTryit() user-defined-javascript-function.


If you want to send information with the GET method, add the information to the URL:-

Code:
httpRequest.open("GET","demo_get2.php?fname=Henry&lname=Ford",true);
httpRequest.send();

POST Requests


A simple POST request:


PHP Code:
httpRequest.open("POST","demo_post.php",true);httpRequest.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:

PHP Code:
httpRequest.open("POST","ajax_test.php",true);httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");httpRequest.send("fname=Henry&lname=Ford"); 

Method => 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:-

PHP Code:
httpRequest.open("GET","ajax_test.php",true); 

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:

PHP Code:
httpRequest.open("GET","ajax_test.php",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:-

  1. execute other scripts while waiting for server response.
  2. deal with the response when the response ready.


Async=true


PHP Code:
httpRequest.onreadystatechange=function()
  {
  if (
httpRequest.readyState==&& httpRequest.status==200)
    {
    
document.getElementById("myDiv").innerHTML=httpRequest.responseText;
    }
  }
httpRequest.open("GET","ajax_info.txt",true);httpRequest.send(); 

If you were surprised from above readyState and Status code 200 than don't worry our next topic on step3 is to discuss about same stuff :)

Async=false


[php
httpRequest.open("GET","ajax_info.txt",false);
[/php]

Using async=false is not recommended, but for a few small requests this can be ok.

Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the send() statement:

PHP Code:
httpRequest.open("GET","ajax_info.txt",false);httpRequest.send();document.getElementById("myDiv").innerHTML=httpRequest.responseText
Server Response


To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

responseText => get the response data as a string.
responseXML => get the response data as XML data.

If the response from the server is not XML, use the responseText property.

PHP Code:
document.getElementById("myDiv").innerHTML=httpRequest.responseText

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

Code:
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i  {
  txt=txt + x[i].childNodes[0].nodeValue + "
";
  }
document.getElementById("myDiv").innerHTML=txt;


Step 2 – Handling the server response


Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.

When a request to a server is sent, we want to perform some actions based on the response.

The onreadystatechange event is triggered every time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

PHP Code:
httpRequest.onreadystatechange nameOfTheFunction
Let's see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response has been received and it's OK for you to continue processing it.
PHP Code:
if (httpRequest.readyState === 4) {
    
// everything is good, the response is received} else {
    
// still not ready

The full list of the readyState values is as follows:

  1. 0 (uninitialized)
  2. 1 (loading)
  3. 2 (loaded)
  4. 3 (interactive)
  5. 4 (complete)


The next thing to check is the response code of the HTTP server response. All the possible codes are listed on the W3C site. In the following example, we differentiate between a successful or unsuccessful AJAX call by checking for a 200 OK response code.

PHP Code:
if (httpRequest.status === 200) {
    
// perfect!} else {
    
// there was a problem with the request,
    // for example the response may contain a 404 (Not Found)
    // or 500 (Internal Server Error) response code

onreadystatechange => Stores a function (or the name of a function) to be called automatically each time the readyState property changes.

readyState => Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready.

status
200: "OK"
404: Page not found

Using a Callback Function


A callback function is a function passed as a parameter to another function.:-

PHP Code:
function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
  {
  if (
xmlhttp.readyState==&& xmlhttp.status==200)
    {
    
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  });


Step 3:- Simple Real Life Example


Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." and then we'll alert() the contents of the test.html file.

PHP Code:
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  
Make a request</span>
<
script type="text/javascript">
(function() {
  var 
httpRequest;
  
document.getElementById("ajaxButton").onclick = function() { makeRequest('test.html'); };

  function 
makeRequest(url) {
    if (
window.XMLHttpRequest) { // Mozilla, Safari, ...
      
httpRequest = new XMLHttpRequest();
    } else if (
window.ActiveXObject) { // IE
      
try {
        
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (
e) {
        try {
          
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (
e) {}
      }
    }

    if (!
httpRequest) {
      
alert('Giving up :( Cannot create an XMLHTTP instance');
      return 
false;
    }
    
httpRequest.onreadystatechange alertContents;
    
httpRequest.open('GET'url);
    
httpRequest.send();
  }

  function 
alertContents() {
    if (
httpRequest.readyState === 4) {
      if (
httpRequest.status === 200) {
        
alert(httpRequest.responseText);
      } else {
        
alert('There was a problem with the request.');
      }
    }
  }
})();



In Above Example :-

  1. The user clicks the link "Make a request" in the browser;
  2. The event handler calls the makeRequest() function with a parameter – the name test.html of an HTML file in the same directory;
  3. The request is made and then (onreadystatechange) the execution is passed to alertContents();
  4. alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.


Note: If you're sending a request to a piece of code that will return XML, rather than to a static XML file, you must set some response headers if your page is to work in Internet Explorer in addition to Mozilla. If you do not set header Content-Type: application/xml, IE will throw a JavaScript error, "Object Expected", after the line where you try to access an XML element. 

Note 2: If you do not set header Cache-Control: no-cache the browser will cache the response and never re-submit the request, making debugging "challenging." You can also append an always-diferent aditional GET parameter, like the timestamp or a random number (see bypassing the cache)

Note 3: If the httpRequest variable is used globally, competing functions calling makeRequest() may overwrite each other, causing a race condition. Declaring the httpRequest variable local to a closure containing the AJAX functions prevents the race condition.

Note 4: In the event of a communication error (such as the webserver going down), an exception will be thrown in the onreadystatechange method when attempting to access the status field. Make sure that you wrap your if...then statement in a try...catch.

PHP Code:
function alertContents(httpRequest) {
  try {
    if (
httpRequest.readyState === 4) {
      if (
httpRequest.status === 200) {
        
alert(httpRequest.responseText);
      } else {
        
alert('There was a problem with the request.');
      }
    }
  }
  catch( 
) {
    
alert('Caught Exception: ' e.description);
  }

Go and See this Live Working Example :- http://www.w3schools.com/ajax/ajax_aspphp.asp


Step 4:- Working with the XML response


In the previous example, after the response to the HTTP request was received we used the responseText property of the request object, which contained the contents of the test.html file. Now let's try the responseXML property.

First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:

Code:


    I'm a test.

In the script we only need to change the request line to:

Code:
...
onclick="makeRequest('test.xml')">
...

Then in alertContents(), we need to replace the line alert(httpRequest.responseText); with:

Code:
var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document. You can see the test.xml here and the updated test script here.


Step 5 – Working with data


Finally, let's send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, test.php, which will take the data we send and return a "computed" string - "Hello, [user data]!" - which we'll alert().

First we'll add a text box to our HTML so the user can enter their name:

PHP Code:
<label>Your name:
  <
input type="text" id="ajaxTextbox" />
</
label>
<
span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  
Make a request</span

We'll also add a line to our event handler to get the user's data from the text box and send it to the makeRequest() function along with the URL of our server-side script:-

PHP Code:
document.getElementById("ajaxButton").onclick = function() {
      var 
userName document.getElementById("ajaxTextbox").value;
      
makeRequest('test.php',userName);
  }; 

We need to modify makeRequest() to accept the user data and pass it along to the server. We'll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send():

PHP Code:
function makeRequest(urluserName) {
    ...
    
httpRequest.onreadystatechange alertContents;
    
httpRequest.open('POST'url);
    
httpRequest.setRequestHeader('Content-Type''application/x-www-form-urlencoded');
    
httpRequest.send('userName=' encodeURIComponent(userName));
  } 

The function alertContents() can be written the same way it was in Step 3 to alert our computed string, if that's all the server returns. However, let's say the server is going to return both the computed string and the original user data. So if our user typed "Jane" in the text box, the server's response would look like this:

{"userData":"Jane","computedString":"Hi, Jane!"}

To use this data within alertContents(), we can't just alert the responseText, we have to parse it and alert computedString, the property we want:

PHP Code:
function alertContents() {
    if (
httpRequest.readyState === 4) {
      if (
httpRequest.status === 200) {
        var 
response JSON.parse(httpRequest.responseText);
        
alert(response.computedString);
    } else {
      
alert('There was a problem with the request.');
    }


The Above Codes are taken from :- w3schools and mozilla developer page to make documentation better and more professional for worldwide people, URL Below :-
https://developer.mozilla.org/en-US/docs...ng_Started
http://www.w3schools.com/ajax/default.asp
 
World of Hacker © 2011 Creative Commons License
World of Hacker by KroKite is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Based on a work at http://www.worldofhacker.com.
Permissions beyond the scope of this license may be available at https://groups.google.com/forum/#!newtopic/hackerforum.