CIS 119 - Ajax hands-on I
Objectives
- create and post a page that uses 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.
Get a fortune
getFortune.php
<?php
passthru("/usr/games/fortune");
?>
getFortune.html
<html>
<head>
<title>Games</title>
<script type="text/javascript">
window.onload = initAll;
var xhr = false;
function $(id) { return document.getElementById(id); }
function initAll() {
getFortune();
$('btnGames').onclick = getFortune;
}
function getFortune() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {}
}
}
if (!xhr) {
$('first').innerHTML = 'Error: Could not make XMLHttpRequest';
} else {
xhr.onreadystatechange = displayFortune;
xhr.open('GET', 'getFortune.php', true);
xhr.send(null);
}
return false;
}
function displayFortune() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var msg = xhr.responseText;
msg = '<p>' + msg.replace(/\n/g, '</p><p>') + '</p>';
$('first').innerHTML = msg;
} else {
$('first').innerHTML = "Error: Did not receive XMLHttpRequest response";
}
}
}
</script>
</head>
<body>
<p id="first"></p>
<p><button id="btnGames">Get new fortune</button></p>
</body>
</html>
Do a simple calculation
docalc.php
<?php
$x = $_GET['x'];
$y = $_GET['y'];
echo $x * $y;
?>
docalc.html
<html>
<head>
<title>Games</title>
<script type="text/javascript">
window.onload = initAll;
var xhr = false;
function $(id) { return document.getElementById(id); }
function initAll() {
$('btnCalc').onclick = calc;
}
function calc() {
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').value
+ '&y=' + $('y').value;
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><input type="text" id="x" /> *
<input type="text" id="y" /> =
<input type="text" readonly="readonly" id="result"></p>
<p><button id="btnCalc">Do calculation</button></p>
</body>
</html>