JavaScript tutorial:
AJAX Tutorial

 

What is AJAX

AJAX stands for Asynchronous JavaScript and XML. It allows you to build web applications and involves at least 3 technologies:

HTML (Hypertext Markup Language) for your web pages
JavaScript, and
XML (Extensible Markup Language) for the data.

Even though it is possible to write code using any text editor or even Notepad, it is time-consuming and error-prone. JavaScript Editor is a tremendous AJAX editor: use it for effortless JavaScript, HTML and XML design.

Why is AJAX great for your web 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.

Example #1

Using loadScript() is amazingly simple. Study the code in the following example to see how everything hangs together.

Click here do download the Example1.zip file. To see the example in action:

Unzip Example1.zip

Run JavaScript Editor and open Example1.htm, and

Click on Show Internal Viewer (or press F5).

To see the example on-line, click here.

Example #1 Examined

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:

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

Below is the content of Example1.htm:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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>
<hr>
<a href="https://c-point.com/javascript_editor.php">Click here</a> for the JavaScript Editor overview<br>
<a href="https://c-point.com/javascript_downloads.php">Click here</a> to view and download additional components for JavaScript Editor<br>
<a href="https://c-point.com/javascript_forum/index.php">Click here</a> to visit the All About JavaScript forum<br>
</body>
</html>

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".

Check it out...

Pregnancy calculator (naturally, coded in JavaScript!)

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.

Example #2

Click here do download the Example2.zip file. You can see it in action on-line (below), or when you upload it to your web server.

To see the example on-line, click here.

Example #2 Examined

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

Data.xml is a simple data file. In this example, we are retrieving the data between the <quote> .. </quote> tags.

<?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>

Tip: for creating, viewing, modifying, editing, and validating XML files in JavaScript Editor, see the section Working with XML files in the manual.

The ajax.js file contains the loadData (URL) function, which does most of the work.

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 <quote> tags
        doSomethingWithData(
             xmlReq.responseXML.getElementsByTagName('quote')[0].firstChild.data);
            break;
        default:
            break;
        }
    }

// Make the request
    xmlReq.open ('GET', URL, true);
    xmlReq.send (null);
}

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, for example:
    https://c-point.com/ajax.php?params=some parameters here

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.htm.

Below is the content of Example2.htm:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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>
<hr>
<a href="https://c-point.com/javascript_editor.php">Click here</a> for the JavaScript Editor overview<br>
<a href="https://c-point.com/javascript_downloads.php">Click here</a> to view and download additional components for JavaScript Editor<br>
<a href="https://c-point.com/javascript_forum/index.php">Click here</a> to visit the All About JavaScript forum<br>

</body>
</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

See also: Working with XML files

For effortless JavaScript, HTML and XML design, use JavaScript Editor, the AJAX editor with incredible power and unmatched ease-of-use.