PutImage is the second project that I plan to use AJAX replace image within HTML page. I know there are a lot of this kind of open source project you can find on web. But as I said, I did these project just for practicing my AJAX coding and sometime just for fun.

Project begin from: 2006, November 23
Version status: Beta 0.2



Okay, now I did the first version of Putimage. As the last project PushMsg I did, I write all the javascript, server side script by myself without using any 3rd party open source component.

If you wanna to see the result for now, please visit sample 1 and you will find it is a very simple example.

How to make it work?

On the web page it need to load an external Javascript file which you can download the latest version from putimage-beta.0.2.js.

Load this Javascript by adding below tag,

<script type="text/javascript" src="http://youHost/path/to/putimage.js"></script>

Bind the PutImage controller to your image component in HTML document by,

<script type="text/javascript">

Please note that, the above your_image.id is the image element's id property. If the component you specified here is not a <img> element. It will alert you the error message this clsPutimg can only be bound to the <img> element.

The function "bind_PutImg_to_object()" tries to bind the PutImage class instance into the specified image element. You can write your script to do the binding instead of the above simple function. I list the original binding function below that you can tell it is a very simple script,

function bind_PutImg_to_object(_obj)
  if (!_obj) return false;
  // Check if the element has already bound the PutImg object
  if (!_obj.PutImg)
    return _obj.PutImg = new clsPutImg(_obj);
    return true;

How it works?

I list the current version (beta 0.2) Javascript below and will explain detailly how this AJAX component works.

function clsPutImg(_obj)
  this.oBound = _obj;
  this.currentIndex = 0;
  this.imageURI = '';

  this.srvURL = '';

     function alertError
  this.alertError = function(_err)
    switch (_err)
      case 201:
        alert('PutImage Error:\r\nYou can only bind "PutImage" class onto a'
              +' <img> element!');
        alert('PutImage Error\r\n(unknown)');

     function init
  this.init = function()
    if (this.oBound.nodeName != 'IMG')
      return false;
    this.imageURI = this.oBound.src;
    return true;
     function go
  this.go = function(_request)
    if (!this.srvURL) return false;
    if (!_request) _request = 'next';
    var _xmlhttp = this.createXMLHttp();
    var _date = new Date();
    _xmlhttp.open('GET', this.srvURL+'?reference='+this.oBound.id+'&request='
                         +_date.getMilliseconds(), true);
    _xmlhttp.onreadystatechange = function()
      if (_xmlhttp.readyState== 4)
        if (_xmlhttp.status == 200)
          var res = _xmlhttp.responseXML;
          var _ref = res.getElementsByTagName('Reference')[0].firstChild.nodeValue;
          var _idx = res.getElementsByTagName('Index')[0].firstChild.nodeValue;
          var _uri = res.getElementsByTagName('URI')[0].firstChild.nodeValue;
          document.getElementById(_ref).PutImg.update(_idx, _uri);

     function update
  this.update = function(_idx, _uri)
    if (_uri == '') return false;
    this.currentIndex = _idx;
    this.imageURI = _uri;
    this.oBound.src = _uri;

     function setServer
  this.setServer = function(_url)
    this.srvURL = _url;
     function createXMLHttp
  this.createXMLHttp = function()
    // Define XMLHttpRequest object
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
     try {
      _xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       _xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       _xmlhttp = false;
    @end @*/
    if (!_xmlhttp && typeof XMLHttpRequest!='undefined') {
    	try {
    		_xmlhttp = new XMLHttpRequest();
    	} catch (e) {
    if (!_xmlhttp && window.createRequest) {
    	try {
    		_xmlhttp = window.createRequest();
    	} catch (e) {
    return _xmlhttp;

  /* initialize the object */
  return this.init();


There are four variables inside this PutImg class definition.

Variable Level Description
oBound Required oBound is the pointer indicate to the <img> parent element.
currentIndex Optional currentIndex is a image sequence number which will send back to server script for indentify the image index within the list in database. If you use my server script then this variable is necessary. But if you write the server script for serve the XML request you can ignore this variable.
imageURI Optional imageURI is the temperary stack to record the current URI of image element. I reserve this variable for next version's image changing animation.
srvURL Required sevURL is the very important variable the indicate the destination XMLHttpRequest send the request to. Although in Javascript the variable is always public that you can directly assign the value to variable, I will still recommend you use the function "setServer(_url)" to assign or change the server side request handler URL.


There are six functions in the PutImg class definition. Although Javascript is not a strict object-oriented program language. You can call the function in class from global or any instance directly. However, I note the significance on the front of description to recommend you how to call these functions.

Function Parameter Return Value Description
init _obj: object boolean Pretected method
Initialize the class when instance be created.
go _request: {next|random} Public method
Create a XMLHttpRequest object and send the request back to server side script. Generate a onreadystatechange event handler for the XMLHttpReqeust before the request send.
update _idx: integer
_uri: string
Protected method
This function is called by the XMLHttpRequest's onreadystatechange event handler. When the response come back from server side, the handler will parse the XML document and call update() function to change the image's URI.
setServer _url: string Set server side script URL.
createXMLHttp object Private method
The standard method used for create a XMLHttpRequest object which compatible to Microsoft Internet Explorer and Mozilla Firefox.
alertError _err: integer Alert the error message which occur during the process.


When user call "go()" function, the PutImg class send XMLHttpRequest to the indicated server URL by GET method with following several parameters.

Parameter Value Type/td> Description
reference string Send the object id which binding PutImg and call the "go()" function.
request string The action item which server should know for the image changing. For example, in my server script I provide two actions: next, random. The "next" action returns the next image on the list. The "random" action returns a randomized image URI from list. You can extend this request parameter for additional action or just for communication between server and client page.
currentIndex integer The current image index. It is only used for informing server which image now the page uses and get the next image on server's list.
rand string A randomized string to abvoid browser caching the request especially the Microsoft Internet Explorer always save the task to send GET request to the same URI.

XML Response

When web page send XMLHttpRequest to server side script, it returns the XML response with the following format.

<?xml version="1.0" encoding="UTF-8"?>
  <Reference>(str)oBound id</Reference>
  <Index>(int)image index</Index>
  <URI>(str)image URI</URI>

Please note that the Reference value should be the same to the value in the reqeust URI.