0

I'm building a contact form that uses ajax via jQuery to fetch a CAPTCHA image (and a hidden data field) and drops it into the form after DOM ready. Also, when the CAPTCHA image is clicked it reloads the image (and the hidden data field).

The CAPTCHA image creation script is of my own creation that I've been using for a couple of years - it's pretty robust and works fine, however this is the first time I've tried integrating it via ajax to a website.

Roughly speaking I've got the following jQuery. I figure the supporting HTML/CSS/PHP is fairly inconsequential - I can supply some if necessary but it all seems to work just fine... the issue appears to be with the jQuery or browser caching with Chrome...

$(document).ready(function() {
    commentFormCaptchaWrapper = $('#captchawrapper');

    // Check DOM for CAPTCHA wrapper... if it's there get the CAPTCHA image
    if (commentFormCaptchaWrapper.length > 0) {getCaptchaImage()}

    // If the CAPTCHA image is clicked get a new one
    commentFormCaptchaWrapper.click(getCaptchaImage);
});


function getCaptchaImage(){
    commentFormCaptchaWrapper.html();
    $.ajax({
        url: '/captcha/ajax.captcha.php',
        type: 'post',
        cache: false,
        success: function(response){
            commentFormCaptchaWrapper.html(response);
        },
        error: function(response){
            alert ("Ajax Error");
        }
    });
}

Everything works exactly how I would like it to in Firefox (and, indeed, Opera and IE) but it doesn't work in Chrome. In Chrome, the initial ajax call for the CAPTCHA image and hidden field works just fine but when you click the CAPTCHA there's a brief flicker as the Captchawrapper div is emptied (so the click is detected OK) but it reloads the same image.

To briefly explain my CAPTCHA script, typically it generates an image based on some text and encrypts the content to use as a file name (with a timestamp suffix) - the image is then cached with a unique name. Therefore, the CAPTCHA script delivers a different file name, completely unique, each time it is used.

I'm not completely up to speed with jQuery yet, however I've turned off ajax caching in the jQuery as far as I'm aware so I just can't figure what's going wrong... can anyone help?

Doug
  • 823
  • 2
  • 10
  • 20
  • 1
    Is there any code you can post from ajax.captcha.php? It might help to see which headers related to caching that you may or may not be setting before you send your response. – Cᴏʀʏ Sep 04 '12 at 13:13
  • Duplicate? http://stackoverflow.com/questions/1742049/jquery-ajax-problem-in-chrome – Ron van der Heijden Sep 04 '12 at 13:21
  • @Bondye - I don't believe this is a duplicate. I read this post previously and it looks like in that example the ajax call is failing. In this example it is working just fine - it just appears to be caching when I don't want it to. – Doug Sep 04 '12 at 13:30

1 Answers1

7

Building on my comment above, there could be two levels of caching happening here (request and response). Using cache: false on the $.ajax call should be enough to prevent request caching at the browser.

At the server level, however, proper response headers must be set for the browser to correctly interpret how it should cache the response. For PHP, a typical set of "do not cache!" headers might look like this (at a minimum):

$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: $ts");
header("Last-Modified: $ts");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");

OTOH, in the answer via the link that Bondye posted, there's another fix:

$.ajax({
    url: '/captcha/ajax.captcha.php',
    type: 'post',
    data: '', // <-- Add this!
    cache: false,
    success: function(response){
        commentFormCaptchaWrapper.html(response);
    },
    error: function(response){
        alert ("Ajax Error");
    }
});

Try adding in a data: '', line to your $.ajax() call. You could also further inspect the data in the error callback to see if there's a weird error code coming back.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • (& @Bondye) - thanks :) Adding the data:'', did the trick just fine, although I don't really understand why. I clearly need to investigate further. Also, do you think I should add the php headers to my serverside script? Even though each time the script is called it returns an image with a different filename? – Doug Sep 04 '12 at 13:34
  • You could have also added a timestamp to the data. That way, your request is different every time and wouldn't be cached. Not sure why the '' works either. – Galway Sep 04 '12 at 13:40
  • @Cory - thanks for the advice. Sorry, I did thank you in my previous comment but your name seemed to fall off somewhere! – Doug Sep 04 '12 at 13:44
  • 1
    @Galway: Adding `cache: false` in the `$.ajax()` properties forces jQuery to automatically append a timestamp to the request URL; there's no need to do it manually as well. – Cᴏʀʏ Sep 04 '12 at 14:43
  • @Doug: Is the filename guaranteed to be unique? Is the timestamp suffix granular enough to behavior correctly if more than one user requested a CAPTCHA image at exactly the same microsecond? I might consider naming the files with a GUID or something slightly more random than a timestamp. Also, adding the headers on the PHP side wouldn't hurt. – Cᴏʀʏ Sep 04 '12 at 14:46
  • @Cory: For the sake of arguement, yes, the filename is absolutely unique - as I tried to point out in my original post (clearly I didn't do it well enough) the filename is generated by encrypting the CAPTCHA word itself into a 32 character string, and then, just to make sure, the time stamp is appended. The only way it might be not unique is if the same word cropped up twice in two separate browsers in exactly the same second... which I suppose is feasible, but massively unlikely. I might reassess the mechanism at some point in the future. – Doug Sep 04 '12 at 15:12
  • @Doug: That seems pretty safe to me. – Cᴏʀʏ Sep 04 '12 at 15:50