Core JavaScript

A Simple AJAX Example

AJAX is a method for retrieving data from a server without refreshing the web page. Below, we have a simple example program to demonstrate how AJAX works. There are three files below which you can create with a text editor. These files are assumed to be in the same folder on the server.

IMPORTANT: These files must be accessed via a web server. That is, they must be on a server or served by a web server on a local machine. For example, if the files are local the program could be run by entering http://localhost:8080/XoaxAjax.html into the address bar of your browser, if the site is set up to run on port 8080. See our video on how to install and use IIS, if you do not know what a web server is.

XoaxAjax.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript AJAX Example</title>
</head>
<body>
  <script type="text/javascript" src="XoaxAjax.js"></script>
  <div id="XoaxDiv"><p>Fill this with the text from XoaX.net's text file.</p></div>
  <button type="button" onclick="LoadXoaxAjaxFile()">Load XoaxAjax.txt</button>
</body>
</html>

XoaxAjax.js

function LoadXoaxAjaxFile() {
	var qhttpReq;
	if (window.XMLHttpRequest) {
		// IE7+, Firefox, Chrome, Opera, Safari
		qhttpReq=new XMLHttpRequest();
	} else {
		// IE6, IE5
		qhttpReq=new ActiveXObject("Microsoft.XMLHTTP");
	}
	qhttpReq.onreadystatechange=function() {
		if (qhttpReq.readyState==4 && qhttpReq.status==200) {
			document.getElementById("XoaxDiv").innerHTML=qhttpReq.responseText;
		} else {
			document.getElementById("XoaxDiv").innerHTML="Error";
		}
	}
	qhttpReq.open("GET","XoaxAjax.txt",true);
	qhttpReq.send();
}

XoaxAjax.txt

<p>The contents of XoaxAjax.txt</p>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.