Monday, May 20, 2013

Just for myself - JavaScript and Ajax

  1. XMLHttpRequest Object  (XHR)
XMLHttpRequest object is used to exchange data with a server behind the scenes.

With XHR we can
  1. Update a web page without reloading the page.
  2. Request a data from a server after the page has loaded.
  3. Receive data from a server after the page has loaded.
  4. Send data to a server in background
Remember: Update, Request, Receive, Send

To find more about XMLHttpRequest, visit  XMLHttpRequest


  • A synchronous XHR example  : The code snippet below illustrates synchronous XHR call. It reads text from a text file named 'data.txt' and presents in the browser. 
    var request = new XMLHttpRequest();
    request.open('GET', 'data.txt', false);
    request.send();
    console.log(request);
    document.writeln(request.responseText);
  • Asynchronous XHR example: The code snippet below illustrates asynchronous XHR call. It reaqds text from a text file named 'data.txt' and presents in the browser. It also takes in consideration the browser type, e.g. it uses XHR request for browsers like Safari, Chrome, Firefox etc and uses ActiveX for Internet explorer.
var request;
/*
If the browser API has XHR object, then set request variable to new XHR object.. for Safari, FireFox, Chrmoe
*/
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else request = new ActiveXObject("Microsoft.XMLHTTP");     // else... for IE
// This makes the script compatible to all browsers
request.open('GET', 'data.txt');  // by default, third parameter is true
request.onreadystatechange = function () {
    if( (request.readyState === 4) && (request.status === 200))
    {
        console.log(request);
        document.writeln(request.responseText);
    }
}
request.send();
Both of the request example above simply writes to a console of a browser.
But we can do the same to modify any part of a web element.


  • getElementById:
    Lets say we have a div element as shown below
    <div id = "heading">
    we can use following DOM command to replace its content as document.getElementById(heading).innerHTML = request.responseText
  • getElementsByTagName:
    Lets say we have some collection of elements, e.g. unordered list as shown below

    <ul>
         <li></li>
         <li></li>
         <li></li>
         <li></li>
         <li></li>
    </ul>


    And we only want to update the third list item, then we can achieve it as shown under.

    var result = document.getElementsByTagName("li");
    result[2].innerHTML = request.responseText



No comments:

Post a Comment