Load External File (Data) With Ajax

by on July 8th, 2007

Here is a simple example of how external data in different files can be called from outside in a single file on some action using Ajax technology. I am writing the code for 5 files. Just copy it. Create same file as mentioned below, named these accordingly paste data in and test it.

example.htm


AJAX Tutorial



AJAX Tutorial: Example 1
This example shows how to dynamically retrieve data from a JavaScript file.

Data File 1
Data File 2
Data File 3

ajax.js
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);
}
Data1.js
doSomethingWithData("Text Data 1 - Hello World");
Data2.js
doSomethingWithData("Text Data 2- Happy Ajaxing");
Data3.js
doSomethingWithData("Data 3 - Example");

And that’s it :)