CIS 119 - Ajax hands-on II
Objectives
- create and post pages that use Ajax to fetch and display information from a server
Hands-on Lab
The point of class today is to develop hands-on experience getting
Ajax up and running on a real web page on a real server.
Updated docalc.html using listboxes
<html>
<head>
<title>Multiply</title>
<script type="text/javascript">
window.onload = initAll;
var xhr = false;
function $(id) { return document.getElementById(id); }
function initAll() {
$('btnCalc').onclick = calc;
}
function getListValue(id) {
var listobj = document.getElementById(id);
if (listobj == null) return null;
if (listobj.type != 'select-one') return null;
for (var i=0; i<listobj.options.length; i++) {
if (listobj.options[i].selected) {
return listobj.options[i].value;
}
}
return null;
}
function calc() {
var x = getListValue('x');
var y = getListValue('y');
if (x==null || y==null) {
alert("Error: Invalid selection");
return false;
}
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {}
}
}
if (!xhr) {
$('result').value = 'Error: Could not create XMLHttpRequest';
} else {
xhr.onreadystatechange = displayResult;
var url = 'docalc.php?x=' + x + '&y=' + y;
xhr.open('GET', url, true);
xhr.send(null);
}
return false;
}
function displayResult() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var msg = xhr.responseText;
$('result').value = msg;
} else {
$('result').value = "Error: Did not receive XMLHttpRequest response";
}
}
}
</script>
</head>
<body>
<p>
<select id="x">
<option value="1">1
<option value="2">2
<option value="3">3
<option value="4">4
<option value="5" selected="selected">5
<option value="6">6
<option value="7">7
<option value="8">8
<option value="9">9
<option value="10">10
<option value="11">11
<option value="12">12
</select>
*
<select id="y">
<option value="1">1
<option value="2">2
<option value="3">3
<option value="4">4
<option value="5">5
<option value="6">6
<option value="7" selected="selected">7
<option value="8">8
<option value="9">9
<option value="10">10
<option value="11">11
<option value="12">12
</select>
=
<input type="text" readonly="readonly" id="result"></p>
<p><button id="btnCalc">Do calculation</button></p>
</body>
</html>