views:

36

answers:

3

I am retrieving a captcha image from the Java based package "SimpleCaptcha"

On the front end I just put the following in my page and I get a captcha image:

<img src="stickyImg" />

I want to reload this captcha image onclick using javascript.

I tried:

$("#theclickhandler").click(function(){  
    $("#stickyImg").load('stickyImg', function(response){           
       $("#stickyImg").attr('src', response); 
    });
    return false;
});

This gets the image but outputs something like this (greatly shortened obviously):

<img src="captcha image�PNG �ݚ��L�23U�݆�}$�J����Dy����IEND�B`� ">

That looks like raw, binary data to me. How do I get this to work?

+1  A: 

You can't use that approach to load images, you need to set the image url attribute to the path of the image generator.

$('#stickImg').attr('src', 'path/to/image/generator');
mikerobi
Well, in the html using <img src="stickyImg" /> (just like that) loads the image. So I figured that to reload it I should use that load method (in my example) to grab the same thing, "stickyImg". I know nothing about java so how do I find the path to the image generator and, more confusingly to me, why does <img src="stickyImg" /> work when the page loads but not when I call it like I do in my load method? Forgive me, I'm a front end guy who has never touched java in my life.
rg88
This isn't sufficient, if the path doesn't change you need to stuff something additional on the URL.
Mark E
+1  A: 

The src attribute of an image tag specifies to the browser where the image to load is, not the content of the image. So you're stuffing the content of the image into the place where you want the location to be, and that's giving you garbage because it simply doesn't make sense.

So, to reload the image, you need to tell the browser that the address of the image has changed. It's not sufficient to simply rewrite the location in the image's src attribute to the same address -- that won't tell the browser to change anything. You can overcome this by stuffing some random data in the query string, say, the time of the request. Like @mikerobi suggests, you can just rewrite the src tag, here with the modification of putting a timestamp in the query string (which your servlet will almost surely ignore):

$('#stickyImg').attr('src', 'stickyImg?' + (new Date().getTime()));
Mark E
Fascinating! I had no idea. That works perfectly though it is close to magic to me. Thank you for explaining the "why" behind this.
rg88
A: 

I don't know how many browsers support it, but it's possible to base64 encode an image, prefix it with (depending on the image format) "data:image/png; base64,", and use that as a URI for the image.

sxeraverx