Alternate Ajax Techniques, Part 2 | 2

Alternate Ajax Techniques, Part 2

Example

Now that you've got the background on this technique, it's time to take a look at a complete example. As with the previous article, this example will be kept simple so that you can understand everything that is going on; the same techniques can be used for more complicated purposes.

The first thing you'll need is a small image, a 1x1 GIF. It's important that this image be as small as possible because you want the response to be as fast as possible. Since this image isn't going to be displayed, it can just be a single white pixel that will download quickly.

Next, a server-side page is necessary to accept input from the query string. The purpose of this page is twofold: to accept the incoming data and set a cookie with outgoing data. Since the request is being made from an image, you need to make sure that the page returns an image, otherwise an error will occur. The best way to do this is to set the content-type of the page to image/gif, set the cookie, then forward the page to the single-pixel image:

    <?php
      header("Content-type: image/gif");
      setcookie("info", "Hello, ".$_GET["name"]);
      header("Location: pixel.gif");
    ?>
This simple PHP page accepts a query string argument of "name," then prepends "Hello" to it. This value is stored in a cookie called "info" for later use. The last line forwards the request to pixel.gif, ensuring a proper image is returned. Save this code in a file named image.php.

Remember the makeRequest() function from the previous article? Here's a recreation of it using images:

    function makeRequest(sUrl, oParams, fnCallback) {
      for (sName in oParams) {
        if (sUrl.indexOf("?") > -1) {
          sUrl += "&";
        } else {
          sUrl += "?";
        }
        sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);
      }

      var oImg = new Image();
      oImg.onload = fnCallback;
      oImg.src = sUrl
    }
You'll notice a lot of similarities between this function and the one used for dynamic script loading. The creation of the URL and its query string parameters is exactly the same. The main difference, aside from using an image, is that a callback function is passed in. This function is assigned to the image's onload event handler before the request is initiated.

Other functions necessary for this example are as follows:

    function getInfo() {
      var oParams = {
        "name": document.getElementById("txtInput").value
      };
      makeRequest("image.php", oParams, handleResponse);
    }

    function handleResponse() {
      alert("Info from server: " + getCookie("info"));
    }
The getInfo() function is called when a button is pressed on the example page. There is a textbox with an ID of "txtInput," into which you can type any value you'd like. That value is passed in as the "name" argument to the query string. Then, the makeRequest() method is called, passing in the URL image.php, the parameters, and the callback function, called handleResponse(). When the response has been received from the server, this function displays the info that it received. You can try it for yourself or download the example.

Note: Some versions of PHP encode spaces in cookies as + instead of %20, in which case you'd have to provide for this in your JavaScript code. If you try this example and see a + in the returned text where a space should be, you'll need to convert them manually to spaces.

Drawbacks

Even though this is an effective way to communicate back and forth with the server, there are several drawbacks and limitations to using this technique.

The first drawback is that it uses cookies. Some browsers restrict cookies based on security settings, and may block cookies without giving any indication of this to the user. Before using this technique, you should test for cookie support by writing a cookie and then reading it back. If the expected value isn't returned, you know that there is no cookie support and so this technique should not be used.

The second drawback is the amount of data that can be stored using cookies. While dynamic script loading had a limit only on the information that was sent to the server, using images and cookies has limits on both he amount of data that is sent and the amount of data that is received. The 4096 byte limit for cookie data is strictly set, and you'll receive no warning if you go over that amount.

And as with dynamic script loading, you can't send a POST request, only a GET request. Make sure that you don't pass any sensitive information in the query string.

Conclusion

In this series, you've learned how to initiate client-server communication without using XMLHttp. Though XMLHttp may be the most complete solution for such communication, both dynamic script loading and the images/cookies technique are valid alternatives, especially if XMLHttp is not available on the client browser. It's up to you as the developer, to decide which technique is appropriate for your needs.

About the Author

Nicholas C. Zakas is a user interface designer for Web applications and the author of Professional Ajax (Wiley Press, ISBN 0471777781) and Professional JavaScript for Web Developers (Wiley Press, ISBN 0764579088). Nicholas can be contacted through his Web site, http://www.nczonline.net/, where he provides open source JavaScript libraries and tools.

Created: March 27, 2003
Revised: March 17, 2006

URL: http://webreference.com/programming/ajax_tech2/1