test.html
<html>
<head>
    <title>AjaxRequest Test</title>
    <script src="ajax.js" type="text/javascript"></script>
</head>
<body>
<input type="button" value="Get time from server" onclick="update();"/>
<input type="text" id="date" size="36"/>
<br/>
<input type="text" id="testpost" size="36"/><input type="button" value="Test post" onclick="testpost();"/>
<br/>
<input type="text" id="testget" size="36"/><input type="button" value="Test get" onclick="testget();"/>
<br/>
<input type="button" value="Test setHeader" onclick="testheader();"/>

<script>
function update() {
	var req = new AjaxRequest();
	req.get(
		{ 
		'url'		: "update.php",
		'onSuccess'	: updateCallback,
		'onLoading'	: function () { window.status="Updating..." },
		'onDone' 	: function() { setTimeout('window.status="done."',250); }
		});
}

// this could be anonymous too, but doesn't have to be...
function updateCallback(req) {  // This is the required signature for a callback
	if (req.responseText) {
		document.getElementById('date').value=req.responseText;
	}
}
	
function testget() {
	var req = new AjaxRequest();
	req.get(
		{ 
		'url'		: "testget.php",
		'onSuccess'	: function (req) { alert(req.responseText); },
		'onLoading'	: function () { window.status="Updating..." },
		'onDone' 	: function() { setTimeout('window.status="done."',250); },
		'params' 	: {
				'foo' : document.getElementById('testget')
				}
		});
}
function testpost() {
	var req = new AjaxRequest();
	req.post(
		{ 
		'url'		: "testpost.php",
		'onSuccess'	: function (req) { alert(req.responseText); },
		'onLoading'	: function () { window.status="Updating..." },
		'onDone' 	: function() { setTimeout('window.status="done."',250); },
		'params' 	: {
				'foo' : document.getElementById('testpost')
				}
		});
}	
function testheader() {
	var req = new AjaxRequest();
	req.get(
		{ 
		'url'		: "testheader.php",
		'onSuccess'	: function (req) { alert(req.responseText); },
		'onLoading'	: function () { window.status="Updating..." },
		'onDone' 	: function() { setTimeout('window.status="done."',250); },
		'headers'	: {
			'foo' : 'AJAX ROCKS'
			}
		});
}

</script>
</body>
</html>



update.php
<?php
print date("r");
?>


testget.php
<?php
print "You sent: " . $_GET["foo"];
?>


testpost.php
<?php
print "You sent: " . $_POST["foo"];
?>


testheader.php
<?php
	print "You sent the following headers: " ;

	foreach($_SERVER as $h=>$v) {
		print "\n\t$h=$v";
	}
?>

Note: The server side code doesn't need to be complicated to be useful... (or even in PHP for that matter)
Back to main page
Back to test page
ajax.js
Source code documentation
Licensed under: Apache License, Version 2.0
If you find this useful, please let me know at: mbreese at gmail dot com
© 2005 Fourspaces Consulting, LLC