Search the Web:

Google

Wednesday, January 9, 2008

Why Ajax for Greater Design

When it comes to web applications, AJAX offers two crucial advantages:

  • It is efficient: only a part of the web page that needs to be modified is being modified. With traditional server-side scripting you send the entire new page to the browser.
  • It is lightweight: only small amounts of data (in the XML form) are being exchanged through the Internet, making your web applications very fast.

How to retrieve static data dynamically

If your web page needs data that is already available (in a file) and does not need to be assembled, here is what to do:

  • Place the data in a .js file, and
  • Use the loadScript() function below to dynamically load and use the .js file you need

function loadScript(scriptURL){

var newScript = document.createElement("script");

newScript.src = scriptURL;

document.body.appendChild(newScript);

}

The loaded script runs immediately in the document context, allowing you to modify page elements as needed.

Lets see the example. First the html file. Save this as Example1.html

<html>

<head>
<title>AJAX Tutorial: Example 1

</title>

<script language="JavaScript" src="ajax.js">

</script>
<script language="JavaScript">

function doSomethingWithData(str){

document.getElementById('MyID').innerHTML = str;

}
</script>

</head>
<body>

<h1>AJAX Tutorial: Example 1

</h1> This example shows how to dynamically retrieve data from a JavaScript file.

<br>

<br>

<input type="button" value="Data file #1" onclick="loadScript('Data1.js')" />

<input type="button" value="Data file #2" onclick="loadScript('Data2.js')" />

<input type="button" value="Data file #3" onclick="loadScript('Data3.js')" />

<p>

<div id="MyID">&nbsp;

</div>

</p>

</body>

</html>

Now, the ajax code in ajax.js file

function loadScript(scriptURL){

var newScript = document.createElement("script");

newScript.src = scriptURL;

document.body.appendChild(newScript);}
function loadData(URL){

// Create the XML request

xmlReq = null; if(window.XMLHttpRequest)

xmlReq = new XMLHttpRequest();

else if(window.ActiveXObject) xmlReq = new ActiveXObject("Microsoft.XMLHTTP");

if(xmlReq==null) return;

// Failed to create the request
// Anonymous function to handle changed request states

xmlReq.onreadystatechange = function() {

switch(xmlReq.readyState) {

case 0: // Uninitialized

break;

case 1: // Loading

break; case 2:

// Loaded

break; case 3: // Interactive

break;

case 4: // Done!

// Retrieve the data between the tags

doSomethingWithData(xmlReq.responseXML.getElementsByTagName('quote')[0].firstChild.data);

break;

default:

break;

}

}
// Make the request

xmlReq.open ('GET', URL, true); xmlReq.send (null);

}

In the Example1.html, we create 3 buttons to get the information in that file on to the page, those files are named as Data1.js, Data2.js and Data3.js

Save the below code as Data1.js

doSomethingWithData("Life is like a dogsled team. If you ain't the lead dog, the scenery never changes (Lewis Grizzard)");

Save the below code as Data2.js

doSomethingWithData("Anyone can steer the ship when the sea is calm (Publilius Syrus)");

Save the below code as Data3.js

doSomethingWithData("A leader is a dealer in hope (Napoleon Bonaparte)");

To better understand what is going on, let us examine all the files being used.

The function loadScript is stored in the ajax.js file. As soon as the specified script file has been loaded, the script inside it is executed. The Data1.js file is used to store or compute the data requested. For simplicity, it only has one line of code:

When the first button is clicked, it calls loadScript('Data1.js'), whick loads and then executes the script in Data1.js. This script passes the data as a parameter to doSomethingWithData (str), which is defined in Example1.htm. In our example, the data is displayed by modifying the div "MyID".

How to retrieve dynamic data dynamically

In many cases, the data is not readily available and must be assembled by a process or from a database. JavaScript does this by using XMLHttpRequest and receiving the content of an xml file in response.
The xml file can then be processed and used to modify various elements on your web page, which is illustrated in Example 2.

Save the html file as Example2.html

<html>

<head>

<script type="text/javascript" src="ajax.js">

</script>
<script language = "JavaScript">

<!--// Function to call with the data retrieved from the XML file function doSomethingWithData(datastr) {

document.getElementById('MyID').innerHTML = datastr;

}//-->

</script>
<title>AJAX Tutorial: Example 2

</title>

</head>

<body>

<h1>AJAX Tutorial: Example 2

</h1> This example shows how to dynamically retrieve data from an XML file. Note: have your web server running on your local machine, or place the example on the web.

<br>

<br>

<input type="button" value="Load data.xml" onclick="loadData('data.xml');" />

<p> <div id="MyID">&nbsp;

</div>

</p>

</body>

</html>

Next take the actual xml file and save it as data.xml

<?xml version="1.0" encoding="utf-8"?>

<root>

<quote>Silence is foolish if we are wise, but wise if we are foolish (Charles Colton)</quote>

</root>

Data.xml is a simple data file. In this example, we are retrieving the data between the <quote> .. </quote> tags. The ajax.js file contains the loadData (URL) function, which does most of the work. The loadData() function creates and then makes the XML request. For the sake of simplicity, the URL is the xml file itself (our Data.xml). In more complex applications, the URL could be a call to a php, asp, or some other process responsible for assembling and returning the XML data. Observe the line xmlReq.onreadystatechange = function(): it defines an anonymous function (in this case) to call whenever the readyState shanges. Here we only process the case when the script is fully loaded: responseXML holds the received XML file, and xmlReq.responseXML.getElementsByTagName retrieves the part of it we are interested in. Similar to our previous example, this script passes the data as a parameter to doSomethingWithData(str), which is defined in Example2.html.

When the button is clicked, it makes a loadData() call to the process that will return the data in the form of an XML file. When the file is fully loaded, doSomethingWithData() is called to process the results. The whole process is illustrated below:
Web browser -> AJAX application -> XML request -> server-side process -> XML file generated -> XML file sent back to XML request -> onreadystatechange received by AJAX application -> data from XML file retrieved/processed -> web browser displays results


No comments:

LinkDirectory.com is a brand NEW 100% SEO friendly and an Entirely human edited link directory.
DaniWeb IT Discussion Community
Blog Search, Blog Directory
Directory of Computers/Tech Blogs