CS75 Lecture #7 Part-1 "AJAX" with jQuery - Building Dynamic Websites
==============================
<!--
ajax1.html
Gets stock quote from quote1.php via Ajax, displaying result with alert().
David J. Malan
Computer Science S-75
Harvard Summer School
-->
<!DOCTYPE html>
<html>
<head>
<script>
// an XMLHttpRequest
var xhr = null;
/*
* void
* quote()
*
* Gets a quote.
*/
function quote()
{
// instantiate XMLHttpRequest object
try
{
xhr = new XMLHttpRequest();
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// handle old browsers
if (xhr == null)
{
alert("Ajax not supported by your browser!");
return;
}
// construct URL
var url = "quote1.php?symbol=" + document.getElementById("symbol").value;
// get quote
xhr.onreadystatechange = handler;
xhr.open("GET", url, true);
xhr.send(null);
}
/*
* void
* handler()
*
* Handles the Ajax response.
*/
function handler()
{
// only handle loaded requests
if (xhr.readyState == 4)
{
if (xhr.status == 200)
alert(xhr.responseText);
else
alert("Error with Ajax call!");
}
}
</script>
<title></title>
</head>
<body>
<form action="quote1.php" method="get" onsubmit="quote(); return false;">
Symbol: <input id="symbol" name="symbol" type="text">
<br><br>
<input type="submit" value="Get Quote">
</form>
</body>
</html>
For a modern browser, there is a thing called XMLHttpRequest (xhr).
It's an object which comes with many methods as follows;
An AJAX call goes through a sequence of states as;
0,1,2,3, and 4. The call sequence from 0 to 2 goes fast. Most people pay attention to only the state 4 (loaded).
An HTML tag <form> is used below.
However, we are not interested in actually submitting a <form>.
Instead, we are making use of the HTTP background process that comes with submitting a <form>.
That's why the "RETURN" value is set to "false".
A variable is named "xhr", but it can be anything.
The variable "xhr" is initialized by setting it to be null.
Since Microsoft IE browser does not fully support the XMLHttpRequest method, a try/catch is setup to accommodate the IE users.
In javascript, document is a DOM object with getElementById() method to read the user input which is a stock symbol for a company name. A stock symbol is a short text string.
A variable called "url" is being constructed, which is really a php script with passing parameters with ?symbol=goog (user input).