Finally dug up an easy enough AJAX sample, and thought I'd share my slight variation on theme. If you put these two files into a dir on a webserver, you can play around a bit with the URL you're calling (URL isn't really a URL and must be relative -- calling off-site URLs seems to cause some security issue where you keep getting nothing back) and what you expect to find in the querystring and post vars. Once you've got this running, you're pretty much raring to go with AJAX. Many examples have more error checking, which would likely be useful, but this is working so I'm going with it for now.

ajax.php
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}

function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
word: <input name="word" value="willBeInPOST" type="text"><br>
url: <input name="url" value="ajaxCatch.php?foo=bar" type="text"><br>

<!-- input value="Go" type="button"
onclick='JavaScript:xmlhttpPost("/cgi-bin/simple-ajax-example.cgi")'></p -->
<input value="Go" type="button"
onclick="xmlhttpPost(document.forms[0].elements['url'].value)"></p>
<div id="result"></div>
</form>
</body>
</html>




ajaxCatch.php
<html>
<head>
<title>Simple Ajax Example</title>
</head>
<body>
Test<br>
<?php
foreach ($_GET as $key => $value) {
$querystring .= $key."=".$value;
}
echo $querystring . "<br>";
foreach ($_POST as $key => $value) {
$strPost .= $key."=".$value;
}
echo $strPost . "<br>";
?>
</body>
</html>

Labels: , , ,