Dave's Brain

Browse - programming tips - easy ajax

Date: 2008oct5
Keywords: sample, kickstart, tutorial

Q.  What's an easy way to get started with AJAX?

A.  Entire books have been written about it but its just not that
hard.  Here's some a simple example.  It displays a button that when
pressed displays the time on the server.

-------8<------------ file get_time.html -------------------------------

<script src=get_time.js></script>
<button onClick="getServerTimeWithAjax()">Get Time on Server</button>

-------8<------------ file get_time.js -------------------------------

// A browser independant function to get the AJAX object.
// I can't say I made this up.
function getAjax() {
	return (!window.XMLHttpRequest)? (new ActiveXObject('Microsoft.XMLHTTP')):(new XMLHttpRequest());
}

// You need a global variable for the request.
var g_req = null;

function stateChange() {
	var result, txt;

	if (g_req.readyState == 4) {
		result = false;
		if (g_req.status == 200) {
			result = true;
			txt = g_req.responseText;
    		}
		g_req = null;	// Set your global to null to show the request is done
		alert('Time on the server is ' + txt);	// Display the result
	}
}

function getServerTimeWithAjax() {
	var url = 'get_time.php';	// Replace with your URL here

	if (g_req != null) {
		g_req.abort();
	}

	// Perhaps set something to show you are working
	// setWorking();

	g_req = getAjax();
	g_req.onreadystatechange = stateChange;	// your handler function (above). Do NOT do "stateChange()"
	g_req.open('GET', url, true);
	g_req.send(null);
}

-------8<------------ file get_time.php -------------------------------

<?
	print strftime('%T', time());
?>
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.