AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 49


PART I


<img src="progressbar.gif" style="display:none;" border="1" id="progressBar" />
<div id="uploadLabel">Server Response</div>
<iframe id="uploadResult" name="uploadresult" width="400"
frameborder="0" height="150" onload="showResult();">
</iframe>

</body>
</html>

Communications Pattern Review


Now that you have seen both one- and two-way JavaScript patterns in action, let’s review
all the general ideas presented so far. The basic communication pattern shown in all these
pre-Ajax methods is roughly as follows:


  1. Trigger communication request (user action or automatic).

  2. Prepare data to be sent to appropriate server-side code.

  3. Form request and wire callbacks if two-way communications.

  4. Send request using appropriate transport method.

  5. If two-way, wait for response informing user to standby.


a. If timeout or error condition, fix or inform user.
b. If successful response received, decode received data.
c. Consume received data, making any required partial page changes; otherwise, if
one-way, make any needed partial page changes without delay.

Note that there are many choices to make along the way. For example, should we use a
query string in a GET request or a POST method typically with a message body? Will
cookies be used as well to pass information or manage state? Should we rely on the browser
standard name-value pairs encoded to the x-www-form-urlencoded MIME type or should
we use another encoding technique? The data to be sent back is also highly variable and
might range from text to HTML fragments including script calls, JSON strings, XML
documents, or even some binary form if appropriate.
All of this communication shouldn’t assume an ideal world. There may be situations
where JavaScript is not on or particular techniques are disallowed. If so, we hopefully
provide a fallback position to another approach or even a standard full-page update style if
possible. If we cannot handle such contingencies, we should either inform users of the site’s
limitations or restrict them from using it in the first place. Even with all communications
techniques available, network conditions and errors also may occasionally occur and we
should address them if possible. At all times, we should design interfaces that give users
some indication of status and put them in control. Unfortunately, even if we are helpful we
can’t be sure of the intentions of our site’s users so we should guard against any possible
malicious activity or data values we may receive on the server-side. Figure 2-9 presents this
brief review in a graphical manner for easy visualization.
Free download pdf