views:

195

answers:

2

I have a web page with lots of small images on it. In a typical scenario user clicks on image and expects it to change with a new image.

Requirements:

  1. When user clicks on image, it should be immediately known to a controller in an Ajax way.
  2. Some strings should be passed to a controller when user clicks on image.
  3. Controller does its job and returns another image (which replaces old one).
  4. Along with image controller returns a couple of extra strings (such as completion status).
  5. Web page updates old image with new one and also updates other parts with these new strings.
  6. Number of images on a page varies but potentially it can be a couple of dozens.

Question: What Ajax technique should be used here? I'm quite new to Ajax and don't feel solid with patterns. Should it be Json or something else?

Any code example would be very very welcome and helpful.

Thank you.

A: 

As far as I known, the only browser-safe way to change an image is by assigning a new URL to it's src attribute. If you return an image to a request that pass some parameters, it might prevent client-side cashing of the images. For these reasons, I would treat separately the transfer of textual data and images. The completion status can always be return as the HTTP status text but if more information is needed from the server, you can always return it in JSON or XML, the simplest being JSON. The responsiveness could be improved by preloading images on the mouseover event.

Maurice Perry
+1  A: 

Well it sounds like you need a Event observer on the image object. On that image object, you could have various custom attributes, such as imageid="2", etc. With the element being observed onclick, you'd read the attributes of the elements and pass them on to an AJAX call. I'm not sure if the image is known by the database or would it be available on the page itself. Maybe a back/previous button? In either case, the AJAX call could either return JavaScript directly which then gets parsed to update the DOM and replaces the image with the new image source, or it could return a JSON response which then needs to get read and parsed by the AJAX callback and then updates the DOM. Easiest being to return JS code which gets parsed, but I prefer to have all my JavaScript in one file and not have it all over the place mixed with server side code.

It really depends on what AJAX library you are using.

With jQuery, you might do something like this.

$("#buttonImage").click(function () {

var imageid = $(this).attr('imageid');

$.getJSON("/controller/get_image/" + imageid, function(data){ $("#buttonImage").attr("src", data.imagesrc); });

});

And your /controller/get_image/123 would return a JSON response like...

{ 'imagesrc' : '/my/image.jpg' }

nshb