Take care of your images

November 19, 2008 — Leave a comment

You might have heard of the double post issue, which causes form data to be sent a second time to the server. This can be resolved by a HTTP redirect after the post has been processed. Today another problem occured to me, one that reminded me of that issue.

I prepared an IMG tag to display a specified image URL by setting the src attribute using JavaScript. The src attribute of that image has been left empty for that purpose (see code below).

function showImage(src) {
  $('imgEl').src = src;
  $('imgWrapper').show();
}

Later I discovered by using [Firebug](http://www.getfirebug.org) that an additional request is being sent to the server. That request used the same path and query string as the original page request used. That way two tickets were added to the shopping cart instead of one. What was keeping me from discovering that issue earlier was that the first response from the server didn’t know yet about the second ticket – so the browser displayed only one ticket in the shopping cart. After reloading the second ticket showed up.

Some JavaScript debugging and HTML commenting later I found out that this behaviour comes from the IMG element with its empty src attribute. Firefox uses the currently called URL for that image to get its content! Even though the wrapping DIV is set to not display it the browser loads that images content.

Happy about figuring out what caused the problem I rewrote the JavaScript mechanism for displaying that specific image. Using the excellent [Prototype Library](http://www.prototypeapi.org) the code snippet would look something like this:

function showImage(src) {
  var wrapper = $('imgWrapper');
  var img = $(document.createElement('img'));
  img.src = src;
  img.alt = 'Don't use an empty src attribute!';
  wrapper.update('');
  wrapper.appendChild(img);
  wrapper.show();
}

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s