sap4help@gmail.com +91 8956877466
This website is always under updation with new contents
Ajax Tutorials
Introduction
Scope and application
Advantage
Disadvantage
Purpose and Process
Request object
Initating a request
Handling Response
Function in ajax
Send request
Ajax GET Request
X in XML
slideDown()
XML File
XML Responding
Prototype & Properties
Ajax testing
Ajax (Asynchronous Javascript And XML)
Introduction
AJAX stands for Asynchronous Javascript And XML
  • AJAX is not a programming language
  • AJAX is a way of using existing standards (JavaScript and XML) to make more interactive web applications
  • AJAX was popularized in 2005 by Google (with Google suggest) not a programming language a particular way of using JavaScript downloads data from a server in the background allows dynamically updating a page without making the user wait aids in the creation of rich, user-friendly web sites
  • Scope and application of ajax
    1. Client opens connection to server
    2. Client sends request to server
    3. Server sends reply to client
    4. Client and server close connection
  • After Step 4, the client renders the document and this may include running some JavaScript
  • In an AJAX application, the JavaScript code then communicates with the server behind the scenes. Communication with the server takes place asynchronously, and transparently to the user
  • Data is exchanged with the server without the need for a page reload
  • This is accomplished through a special kind of HTTP request
  • Advantage
  • Allows web applications to interact with data on the server
  • Avoid clunky GET/POST send/receive interfaces – web apps look more and more like real applications
  • Some applications can only be realized this way
    Eg: Google Suggest offers interactive access to one of the largest data collections in the world

    For office style applications, user's data is stored on a reliable erver, accessable from any web browser.

    Disadvantage
  • Tough to make compatible across all browsers
  • Should have a low-latency connection to the server
  • Can be server intensive
    Eg: Google Suggest generates a search for every keystroke entered.
    Ajax purpose and process
    Define an object for sending HHTP request.
    Initiate request.
    Get request object.
    Designate an anonymous response handler function.
    Initiate GET or POST request.
    Send data.
    Handle response.
    Wait for ready state of 4 and Http status of 200.
    Extract return text with response text or response XML.
    Do something with result.
    Defining a Request object
    function getRequestObject() 
    {
    if (window.XMLHttpRequest)
     {                                      
           return(new XMLHttpRequest());
    } 
    else if (window.ActiveXObject) 
    { 
    return(new ActiveXObject("Microsoft.XMLHTTP"));
    }
     
    else
    {
    return(null); 
          }
    }

    Special things that are used in defining these object.

    1. XMLHttpRequest()= version for firefox,netscape 5+,opera,safari,mozila chrome, internet explorer 7,and IE 8.
    2. ActiveXObject = version for internet explorer 5.5 and 6
    3. return(null); = Fails on older and nonstandard browsers. You don’t want to do “throw new Error(...)” here because this is for very old browsers, and Error came only in JavaScript 1.5
    Initating a request
    function sendRequest() {
    var request = getRequestObject();
    request.onreadystatechange = function() 
    { 
    handleResponse(request)
     };
    request.open( “GET”, “message-data.html”,true);
    request.send(null);
    }
    Some important points
    handleResponse(request) = Code to call when server responds
    message-data.html = URL of server side resource Must be on same server that page was loaded from.
    True = Don't wait for response (Send request asynchronously)
    (null) = POST data (always null for GET request)
    Pictorial representation of request object
    Handling Response
    function handleResponse(request) {
    if (request readyState == 4) 
    {
    if(request.readyState ==4)
     {
    alert(request.responseText);
     }
    }
    Some important points
    4 = 4 means response from server is complete (handlers get invoked multiple times ignore the first times)
    responseText = Text of server response
    alert = Pop up dialog box
    Function in ajax
    The open function of an XML HTTP request takes three arguments
    1. xmlHttp. open(method, uri, async)
    2. method is either "GET" or "POST"
    3. uri is the (relative) URI to retrieve
    4. async determines whether to send the request
    5. asynchronously (true) or synchronously (false)
    6. The domain of the uri argument must be the same as the domain of the current page
    The send function takes one argument
    xmlHttp. send(content);
    content is the content to send (useful when
    method="POST")
    Send request
    function sendRequest()
    var xmlHttp = GetXmlHttpObject();
    if (! xmlHttp) {
    return false;
    }x
    mlHttp. onreadystatechange = function() {
    if (xmlHttp. readyState == 4) {
    alert("Request complete");
    }
    }
    var requestURI =
    "http: //myserver. org/somepage. txt";
    xmlHttp. open("GET", requestURI, true);
    xmlHttp. send(null);
    }
    property of ready state change events
    holds the status of the XMLHttpRequest
    possible values for the readyState property:
    readyState changes → onreadystatechange handler runs
    usually we are only interested in readyState of 4 (complete)
    Asynchronous XMLHttpRequest template
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
    if (ajax.readyState == 4)
     {   				  // 4 means request is finished
    do something with ajax.responseText;
    }
    };
    ajax.open("get", url, true);
    ajax.send(null);
    The XMLHttpRequest object is used for exchanging data with a server behind the scenes.
    Find request error
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
    if (ajax.status == 200) 
    { 				// 200 means request succeeded
    do something with ajax.responseText;
    } else {
    code to handle the error;
    }
    }
    };
    ajax.open("get", url, true);
    ajax.send(null);
    Some important points
    1. An XMLHTTPRequest object can send the request to any URI as long as it has the same domain as the page that requests it.
    2. This URI can refer to a CGI script or even just an HTML document.
    3. Note the big security risk for the client JavaScript can send anything to the server Client needs to restrict what JavaScript has access to.
    Ajax GET Request
    X in XML
    1. The X in AJAX comes from XML
    2. In an XML HTTP request, we usually expect the

    server to respond with some XML

    3. What is XML?

    A specification for creating languages to store data; used to share data between systems a basic syntax of tags & attributes languages written in XML specify tag names, attribute names, and rules of use Example: XHTML is a "flavor" of XML

    4. Short answer: like HTML but You can make up your own tag names
    All tags have to be closed (and there is a shorthand)
    Uses of XML
  • XML data comes from many sources on the web
  • web servers store data as XML files
  • databases sometimes return query results as XML
  • Web services use XML to communicate
  • XML languages are used for music, math, vector graphics
  • XML file

    the new tags (we just made them up)

    An XML version number

    One tag contains everything (and becomes the root of the document tree)

    <?xml version="1. 0" encoding="ISO-8859-1"?>
    <note>
    <to>saplogic</to>
    <from>help4code</from>
    <heading>Reminder</heading>
    <body>Largest collection of programs</body>
    </note>
    XML Responding
    1. We can look at the XML text within a response using the responseText property.
    2. Even better, we can use the responseXML property to access the XML.
    3. Best, responseXML. documentElement contains the document tree for the XML.
    4. This is a document tree in the DOM model that we've seen before (just like document).
    Example
    function sendRequest() {
    var xmlHttp = GetXmlHttpObject();
    if (! xmlHttp) {
    return false;
    }x
    mlHttp. onreadystatechange = function() {
    if (xmlHttp. readyState == 4) {
    var xmlDoc =
    xmlHttp. responseXML. documentElement;
    }
    }v
    ar requestURI = xmlURI;
    xmlHttp. open("GET", requestURI, true);
    xmlHttp. send(null);
    }
    Prototype Ajax methods and properties
    Options

    That can be passed to the Ajax.Request constructor:

    method : how to fetch the request from the server (default "post" )
    parameters : query parameters to pass to the server, if any asynchronous (default true), contentType, encoding, requestHeaders events in the Ajax.Request object that you can handle:
    onSuccess : request completed successfully
    onFailure : request was unsuccessful
    onCreate, onComplete, onException, on### (handler for HTTP error code ###)
    Ajax testing on browser
  • If you field an internal application, test on all officially sanctioned browsers on all supported operating systems.
  • If you field an external application, test on as many browsers as possible. Preferably: IE 6, IE 7, IE 8, a recent Firefox implementation, and Chrome. Safari and Opera can’t hurt, but are less used less used.
  • Test regularly on IE and Firefox. Test on Chrome and a wider set of browsers before deploying.
  • Browser market share: htt //p://www.w3 h l /b /b t tschools.com/browsers/browsers_stats.asp
  • Access stats on coreservlets.com (August 2010) – IE: 42.4%, Firefox: 41.1%, Chrome: 12.8%, Safari: 1.4%, Opera: 1.3%

  • For accessing computer programs go to TECHNOLOGY