Alternate Ajax Techniques, Part 1 | 2 | WebReference

Alternate Ajax Techniques, Part 1 | 2

Alternate Ajax Techniques, Part 1

Next, you need a way to assign the callback function to be used. It's quite possible that you'll want to access the same information on different pages and in different ways. Forcing each page to have a callback function named "callback" isn't very good architectural design. Instead, it would be better to tell the JavaScript file the name of the callback function to use so that it can be dynamically inserted. The name of the function can be passed as another parameter for the query string:

var oParams = {
  "param1": "value1",
  "param2": "value2",
  "callback": "myCallbackFunc"
makeRequest("/path/to/myjs.php", oParams);

The file creating the JavaScript then has to take the name of the callback function and output it into the code, as below:

   header("Content-type: text/javascript");

var sMessage = "Hello world!";
<?php echo $_GET["callback"] ?>(sMessage);

The first part of this file sets the content type to text/javascript so that the browser recognizes it as JavaScript (though many browsers don't check the content type of files loaded using <script/>). Next, a JavaScript variable called sMessage is defined as a string, "Hello world!". The last line outputs the name of the callback function that was passed through the query string, followed by parentheses enclosing sMessage, effectively making it a function call. If all works as planned, the last line becomes:


Example 2

This example builds upon the previous one, but this time, you're going to send some additional information to the server and tell it which callback function to call. First, take a look at the PHP file that will be outputting the JavaScript:

    header("Content-type: text/javascript");

var sMessage = "Hello, ";
var sName = "<?php echo $_GET['name'] ?>";

<?php echo $_GET['callback'] ?>(sMessage + sName);

The JavaScript that will be output defines two variables, sMessage and sName; the former is filled with "Hello, ", the latter is assigned the value of the name parameter in the query string. Then, the name of the callback function is out, passing in the concatenation of sMessage and sName (combining server-side data with data passed from the client).

On the client side, the web page contains a textbox and a button:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="">
    <title>Example 2</title>
    <script type="text/javascript">//<![CDATA[
      function makeRequest(sUrl, oParams) {
        for (sName in oParams) {
          if (sUrl.indexOf("?") > -1) {
            sUrl += "&";
          } else {
            sUrl += "?";
          sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);

        var oScript = document.createElement("script");
        oScript.src = sUrl;

      function messageFromServer(sText) {
        alert("Loaded from file: " + sText);

      function getInfo() {
        var oParams = {
          "name": document.getElementById("txtInput").value,
          "callback": "messageFromServer"
        makeRequest("example2js.php", oParams);

    <input type="text" id="txtInput" value="Nicholas" />
    <input type="button" value="Get Info" onclick="getInfo()" />

When the button is clicked, the getInfo() method is called, which loads an object with a name parameter (taken from the textbox) and a callback parameter. Then, the makeRequest() function is called, passing in these values. After the script has been loaded, the messageFromServer() function will be called, popping up a message displaying what was received from the server. Try it for yourself or download both examples.


Though dynamic script loading is a quick and easy way to establish client-server communication, it does have some drawbacks. For one, there is no feedback once the communication is initiated. If, for example, the file you are accessing doesn't exist, there is no way for you to receive a 404 error from the server. Your site or application may sit, waiting, because the callback function was never called.

Also, you can't send a POST request using this technique, only a GET, which limits the amount of data that you can send. This could also be a security issue: make sure you don't send confidential information such as passwords using dynamic script loading, as this information can easily be picked up from the query string.


Though XMLHttp is the most talked-about method for client-server communication in Ajax, dynamic script loading is a perfectly acceptable and serviceable alternative. The examples in this article were relatively simple, but it shouldn't be difficult to extend the techniques presented to accomplish more interesting results.

In the next part of this series, you'll learn how to use images and cookies to establish Ajax functionality that works in nearly every browser that supports JavaScript.

About the Author

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

Created: March 27, 2003
Revised: February 10, 2006