CIS 119 - Ajax
Objectives
- use Ajax to modify a page without reloading it
- use an Ajax toolkit
- use Ajax to modify the formatting on a page
Ajax
- Ajax stands for Asynchronous JavaScript And XML, although the claim
is made that it is actually not an acronym, just an abbreviation/nickname.
- Ajax makes heavy use of JavaScript and X/HTML. Ajax web pages often rely
on a lot of CSS also.
- Ajax is not a new language. It is based upon the JavaScript XMLHttpRequest
object, which can be used to send and receive data from a server from within
a web page. This enables web pages to become much more interactive and be modified
with server-side data without having to reload a page or use frames.
- The XMLHttpRequest object is used to exchange small amounts of data rather
than whole pages. The XML part of Ajax was meant to stand for the format the
data is transferred in, although nothing forces you to use XML. Many applications
use the simpler JSON format. We will use an even simpler format, plain text.
- Microsoft invented XMLHttpRequest, but Google made it popular in 2005 with their
Google Suggest feature, which shows you a list of suggestions from the Google
servers while you are still typing in the search box.
- We will demonstrate the use of Ajax with a simple application that uses a server
script to reverse names. See the next two sections for the code. Keep in mind that
this has to be running on a server to work.
- Although Ajax was originally intended to fetch data from a server without
reloading a web page, Ajax toolkits are often used just for their cross-browser
utility libraries, especially for special effects.
- There are many Ajax toolkits available: prototype, scriptaculous, jQuery, Dojo,
YUI, MochiKit, and many more
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']));
?>