AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 413


<div id="question">
<h3>How do you feel about Ajax?</h3>
</div>
<em id="minRating">Hate It - </em>
<span id="ratings"> [
<input type="radio" name="rating" value="1" /> 1
<input type="radio" name="rating" value="2" /> 2
<input type="radio" name="rating" value="3" /> 3
<input type="radio" name="rating" value="4" /> 4
<input type="radio" name="rating" value="5" /> 5
] </span>
<em id="maxRating"> - Love It</em>
<br /><br />
<input type="submit" value="vote" />
</form>

</div>
<!-- rating widget: END -->

You’ll note that the example just uses the form target to present the results in another
window so that the in-page concept can be preserved. The new window contains a full page
with appropriate markup showing the vote and results.
Now if a browser supports JavaScript, it would be better to provide a much richer
interface and use an Ajax transport. First, a <noscript> tag is used to hide the submit
button from the Ajax version and to add a hidden form field to the non-Ajax version which
will be used to indicate to the server-side program we are not performing an Ajax request.

<noscript>
<input type="hidden" name="transport" value="downgrade" />
<input type="submit" value="vote" />
</noscript>

You may wonder why we are doing this since in some sense we are progressively
enhancing it. Wouldn’t it make more sense to present the very basic markup and then
remove the items that we are not using with script? Maybe, but then we would potentially
have to address screen flashing as items are removed. With that said, it would seem a good
idea to bury all the radios within the <noscript> as well. That is an option, but the script
needs to count the radios to determine how many rating choices to insert and, unfortunately,
DOM methods in most browsers cannot address items within the <noscript> tag. The
solution we present is, like much of Web development, as elegant as it can be.

Building a Rating Widget


When the page completes loading, our Ajaxified rating widget is initialized. We adopt a
simple convention of namespaces, prefixing our widgets with AjaxTCR.widget, so in
this case, we have AjaxTCR.widget.ratingWidget. We will also adopt a convention
that all our widgets should be initialized via public method init(), so we would invoke
AjaxTCR.widget.ratingWidget.init() upon page load to bind this widget into our
example document. However, to bind the widget safely so that it does not override
existing scripts already in the page, we also introduce a new library utility method
Free download pdf