Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Wednesday, May 22, 2013

Parsing XML using AJAX

Hi friends,

Lets say we have an XML file named "data.xml" as shown below.


<?xml version="1.0" encoding="utf-8" ?>
<speakers>
  <speaker>
    <name>LaVonne L. LaRue</name>
    <shortname>LaVonne_LaRue</shortname>
    <reknown>Chicago, IL</reknown>
    <bio>LaVonne's giant-sized paintings all around Chicago tell the story of love, nature, and conversation - themes that are central to her heart. LaVonne will share her love and skill of graffiti art on Monday's schedule, as she starts the paintings of a 20-foot high wall in the Rousseau Room of Hotel Contempo in front of a standing-room only audience in Art in Unexpected Places.</bio>
  </speaker>
  <speaker>
    <name>Samuel Deji Eniojukan</name>
    <shortname>Sam</shortname>
    <reknown>Atlanta, GA</reknown>
    <bio>Sam is expert sharepoint architecture.</bio>
  </speaker>
  <speaker>
    <name>Suraj Shrestha</name>
    <shortname>Suraj</shortname>
    <reknown>Boston, MA</reknown>
    <bio>Suraj is expert .NET programmer.</bio>
  </speaker>
  <speaker>
    <name>Hari Paudel</name>
    <shortname>Honey</shortname>
    <reknown>Jackson Heights, NY</reknown>
    <bio>Hari is expert MVC developer.</bio>
  </speaker>
  <speaker>
    <name>Merin Nakarmi</name>
    <shortname>Merin</shortname>
    <reknown>Atlanta, GA</reknown>
    <bio>Merin is expert SharePoint and .NET Developer/Architecture.</bio>
  </speaker>
  <speaker>
    <name>Tchelen Lilian Costa Nakarmi</name>
    <shortname>Tchelen</shortname>
    <reknown>Manaus, AM, Brazil</reknown>
    <bio>Tchelen is sweet clarinest girl.</bio>
  </speaker>
</speakers>

And we have a html file named index.html as shown below.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>JavaScript Ajax</title>
</head>
<body>
    <h1>AJAX page</h1>
    <div id="speakers">
    </div>
    <script src="script.js" type="text/javascript">
    </script>
</body>
</html> 

Now, we want to display the contents of the XML data file to a html page. We only want to display the list of name of speakers in the div with id "speakers". For this, we have an external JavaScript file named "script.js" as shown below.


var request;

if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', 'data.xml');

request.onreadystatechange = function () {
    if((request.readyState === 4) && (request.status === 200))
    {      
        var items = request.responseXML.getElementsByTagName('name');
        var output = '<ul>';
        for (var i = 0; i < items.length; i++) {
            output += '<li>' + items[i].firstChild.nodeValue + '</li>';
        }
        output += '</ul>';

        document.getElementById('update').innerHTML = output;
    }
}

request.send();


The output of the  html file would look like


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