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
<html>
<head>
<title>AJAX Tutorial</title><script language="JavaScript" src="ajax.js"></script>
<script language="JavaScript">
function doSomethingWithData(str)
{
document.getElementById('MyID').innerHTML = str;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
<!--
body,td,th {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
color: #666666;
}
-->
</style></head>
<body>
<b>AJAX Tutorial: Example 1</b><br />
This example shows how to dynamically retrieve data from a JavaScript file.<br /><br />
<a href="#" onClick="loadScript('Data1.js')">Data File 1</a><br />
<a href="#" onClick="loadScript('Data2.js')">Data File 2</a><br />
<a href="#" onClick="loadScript('Data3.js')">Data File 3</a><br />
<br />
<div id="MyID"> </div>
</body>
</html>
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 <quote> 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 :)


Share