CIS 119 - Ajax

Objectives

Ajax

Demonstrations

Ajax XMLHttpRequest demonstration - HTML page

<html>
<body>
<script type="text/javascript">

function getRequestObject() {
   if (window.XMLHttpRequest) return new XMLHttpRequest();
   else if (window.ActiveXObject)
      return new ActiveXObject("Microsoft.XMLHTTP");
   alert("Your browser does not support AJAX!");
   return null;
}

function $(n) { return document.getElementById(n); }

function doStuff() {
   var req = getRequestObject();
   if (req == null) return false;
   req.open("GET","reverse.php?text=" + $('txt1').value,true);
   req.send(null);
   req.onreadystatechange = function() {
      if(req.readyState==4) {
         $('result').innerHTML = req.responseText;
      }
   };
   return false;
}

</script>
<form onsubmit="return doStuff();">
Input: <input type="text" id="txt1" /><br />
<input type="submit" value="Reverse It" />
</form>
<div id="result">
</div>
</body>
</html>

Ajax XMLHttpRequest demonstration - PHP script

<?php
   if (isset($_GET['text']))
   echo strrev(stripslashes($_GET['text']));
?>