AJAX - The Complete Reference

(avery) #1

384 Part II: Developing an Ajax Library^


/* kill default submit of a single field form */
document.requestForm.onsubmit = function(){return false;};
};
</script>
</head>
<body>
<div class="content">
<h2>Auto Suggest</h2>
<form action="#" method="get" name="requestForm">
<label>Enter a Country:<br />
<input type="text" name="country" id="country" autocomplete="off" /><br />
<div id="suggestList"></div>
</label>
</form>
</div>
</body>
</html>

If after exploring this example you begin to worry a bit about going to the network quite
a bit or fetching data that is never used, you aren’t alone. There is clearly a trade-off with
this application of Ajax. If you want users to filter a large data set, particularly when their
entries are quite large, this is a wonderful use of Ajax, especially if you can keep your
response time low. However, with less data, short entries, or a slow connection this
approach might create problems for some users even if it solves it for others.

Auto Search


A variation of the previous pattern of using Ajax to quickly provide data suggestions would
be to actually immediately perform a task with the incrementally fetched content. As an
example, users could be allowed to type in keywords and phrases that would automatically
have a search performed upon. This pattern is even more aggressive than the previous one
in terms of resource utilization, but it does provide the user with instant search gratification,
as well as providing a sense of narrowing data.
The following is a form field query for the user to enter search terms:

<form name="requestForm" action="#" method="get">
<label>Search Term:
<input type="text" name="query" id="query" autocomplete="off"
size="100" /></label></form>

The field is probed every second by calling the function getSuggestions() using
setInterval(). When the user blurs the field, it is assumed that they are focused on what
is there so the interval is cleared.

window.onload = function ()
{
document.requestForm.query.onfocus = function(e){gTimer = window
.setInterval(function(){getSuggestions();}, 1000);};
document.requestForm.query.onblur = function(e){window.clearInterval
Free download pdf