Ajax Fundamentals – Part 2

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

2. Ajax Communication

2.1. Handling the Server Response

The XMLHttpRequest object is used to receive the sever response. Two methods are used, namely responseText and responseXML. The responseText method returns text and the responseXML returns an object that can be parsed as a DOM object.

The responseText is limited however its functionality can be enriched when combining it with the innerHTML property. This is a simple method of including dynamic content within the page. The following code is a selected code extract from an example supplied by Foundations of Ajax.


function startRequest()
{
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "innerHTML.xml", true);
    xmlHttp.send(null);
}
function handleStateChange()
{
    if(xmlHttp.readyState == 4)
    {
        if(xmlHttp.status == 200)
        {
            document.getElementById("results").innerHTML =                 xmlHttp.responseText;
        }
    }
}


  <body>
    <form action="#">
      <input type="button" value="Search for Today's Activities" onclick="startRequest();"/>
    </form>
<div id="results"></div>
</body>

The above example refers to “innerHTML.xml”. This is a document that contains HTML tags that define an HTML table. When handleStateChange executes, an HTML table is embedded between within ‘results’ div tags and a table will be displayed.The innerHTML property is not a standard therefore not all browsers offer the same support. Microsoft Internet Explorer restricts innerHTML property to read only on certain elements. Using the W3C DOM is the preferred method for manipulating the web page. In order to use the W3C DOM the script needs to extract specific data from the server’s response. Selecting data from XML is far simpler than finding the data in plain text. The script can use responseXML to receive a response in XML format.The responseXML method returns an XML object that meets the W3C DOM specification. This standard is supported by most modern browsers. Using the API provided by DOM, the script can traverse the XML document. The following code shows an example of this.


function showArtistAlbums(artist)
{
    var artistname = artist;
    var xmlDoc = req.responseXML;// req is an XMLHttpRequest object
    var node = xmlDoc.getElementsByTagName(artistname)[0];
    var albums = node.getElementsByTagName("album");
    var result = artistname;

    for(var i = 0; i < albums.length; i++)
    {
        result = result + "n * " + albums&#91;i&#93;.                         childNodes&#91;0&#93;.nodeValue;// Retrieves the text value
    }
}

&#91;/sourcecode&#93;

The objective of Ajax is to modify only relevant parts of a web page without refreshing the entire page.   This eases the load on the web server and provides a better user experience.   Performing these ‘precision updates' is possible by making use of the W3C DOM. <a href="http://www.amazon.com/Foundations-Ajax-Foundation-Ryan-Asleson/dp/1590595823/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1207069447&amp;sr=8-1" target="_blank">Foundations of Ajax gives a good example of dynamically appending rows to an HTML table.   A Sample of the code is shown below.   Note that the tbody tag is used, in this case the tbody element has an ID equal to "resultsBody".



function addTableRow(address, price, comments)
{
    var row = document.createElement("tr");
       var cell = createCellWithText(address);
       row.appendChild(cell);
       cell = createCellWithText(price);
       row.appendChild(cell);
       cell = createCellWithText(comments);
       row.appendChild(cell);
       document.getElementById("resultsBody").appendChild(row);
}
function createCellWithText(text)
{
       var cell = document.createElement("td");
       var textNode = document.createTextNode(text);
       cell.appendChild(textNode);
       return cell;
}

Continue reading

Ajax Fundamentals – Part 1

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

1. Introduction to Ajax

On the 18’th of February 2005 Jesse James Garret introduced the term Ajax in an article called “Ajax: A New Approach to Web Applications“. That article explained that Ajax is an acronym for Asynchronous JavaScript and XML. It is a way of using existing web-based technologies to provide a rich user interface to websites. It is a design pattern and not a new language and it is not a W3C standard.

In his article, Jesse Garrett lists the properties of Ajax:

  • standards-based presentation using XHTML and CSS
  • dynamic display and interaction using the Document Object Model
  • data interchange and manipulation using XML and XSLT
  • asynchronous data retrieval using XMLHttpRequest
  • and JavaScript binding everything together

In order for a classic web page to respond to a users input, an HTTP request needs to be sent to the server. The server processes the input and replies with an HTML page. Thus the entire page needs to be reloaded in order to provide a response to the user. This request/reply model can be tedious for a user. Ajax proposes a different model.Using the Ajax method a script can send asynchronous HTTP requests from the browser to the server. The script is notified when the response arrives at the browser, and can process the response. Units of data can be requested and processed without the user being disrupted by a complete page refresh. Garrett provides a graphical depiction of the Ajax model in the following image.

Ajax Fundamentals - Life Cycle

Continue reading

Ajax Fundamentals – About & Index

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

About This Series

Silverlight, Apollo, JavaFX have spurred another wave of Rich Internet Application discussions. I came across an interesting interview with David Heinemeier Hansson, the creator of Rails.

In this interview Hansson states: “We went through this with Java applets, they were going to rule the Web. Everything was going to be in a Java applet. HTML and CSS is history. And Flash came around, and Flash started focusing on applications. Now Flash is going to rule the Web and HTML and so on is yesterday. Now, Silverlight, Apollo, JavaFX, they’re all bidding to take over the JavaScript, HTML and CSS [spaces], and I just don’t buy it.”

Hanson also made this comment: “I think that there are misconceptions going on from people who are pushing these alternative delivery platforms that somehow Web developers are hungry for richer and richer experiences, that they’re really unhappy working with HTML and CSS. And that’s just not true. We’re not clamoring to re-create the desktop on the Web.”

Hansson makes a good point, developers will not be throwing away HTML and CSS any time soon. Therefore I have decided to create this series to explore the different facets of developing with Ajax.

Index

Part 1
1. Introduction to Ajax
2. The XMLHttpRequest Object
2.1. The Document Object Model
2.1.3. DOM Levels

Part 2
2. Ajax Communication
2.1. Handling the Server Response
2.2. Parsing Parameters in the Request
2.3. JavaScript Object Notation

Part 3
3. Security Issues
4. Disadvantages
4.1. Usability Problems
4.2. JavaScript Disabled
4.3. Search Engine Indexing

Part 4
5. Development and Debugging Tools
5.1. Documenting JavaScript
5.2. Firefox Tools & Extensions
5.3. JavaScript Syntax Checking
5.4. Compression and Obfuscation

Part 5
6. Summary

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 2 of n

Part 3

Thank you to all of you who took the time to give me feedback on part 1. Most of the feedback was positive. A friend of mine suggested that I drop the sound effects and stick to the subject matter, I graciously accepted his advice. Therefore this post should have a better fact to fluff ratio than the previous one. On that note, let’s begin…

Part 2

In part 1 we learnt that the routing system has two main functions:
• Interpreting a request URL
• Generating a request URL
Rails uses the same routing rule to interpret a URL and to generate a URL.
Note that routing rules are often called routes, I will use the terms interchangeably.

Now we will start fixing our music_store application from part 1.

Continue reading

Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 1 of n

Part 2

About this series

This is a series for beginners wanting to learn about routing in Rails 2.0. This first post is aimed at exploring the behaviour of routing in Rails. It examines what happens when the routing system is given a certain URL. Future posts will examine the ‘hows’ and ‘whys’ of this behaviour. The plan is to start with the basics and move towards the advanced topics. There is only a brief mention of RESTful routing in this post. I plan to delve deeper into that topic at a later stage.

Introduction

The routing subsystem is at the heart of a Rails application. By looking at the following image, we can see the role of the routing system.

RoutingInRails

The diagram is a modified version of a diagram found in Flexible Rails.

As the picture depicts, in a Rails application the process begins with a request from the browser. This request is passed into the Rails routing system. The routing system examines the request and is able to determine the following information:

  • Which controller to instantiate
  • Which action (method) to invoke on that controller
  • The parameters, if any, to pass into the action

When receiving a correctly formatted request URL the routing system will instantiate the specified controller, call the appropriate action and pass in the supplied method parameters, if required. The controller will then perform the necessary action and Rails will render the relevant view. This will result in the browser receiving a response and the round trip is complete. This is oversimplified, but it does show the importance of the routing system.

If the request is not in the correct format the routing system may not be able to infer the correct action to take. Therefore it is important that the format is correct. We are in luck as the Rails routing system also helps us to generate requests in the correct format.

In short, the routing system has two main functions:

  • Interpreting a request URL
  • Generating a request URL

The routing system performs these functions by using routing rules, defined in Ruby code as opposed to XML. The rules can be found in the config/routes.rb Ruby file. Each rule is used to both interpret and to generate a related request URL.

I could go into more theory here but, as with many things, the best way to get to grips with routing is to do it!

Continue reading