tags:

views:

245

answers:

3

I need to put a one second delay in this jQuery function so that when the captcha is filled in correctly, there is a sufficient delay (one second, I think) for the #captchaStatus to show before the next step of the process (which is a html being posted).

Must be fairly easy, though I'm learning jQuery.... Ideas? Thanks.

function validateCaptcha()
{
    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    //alert(challengeField);
    //alert(responseField);
    //return false;
    var html = $.ajax({
    type: "POST",
    url: "/wp-content/themes/default/ajax.recaptcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
    async: false
    }).responseText;

    if(html == "success")
    {
        $("#captchaStatus").html("You got it right - I'm sending the email now....");
        return true;
    }
    else
    {
        $("#captchaStatus").html("Your captcha is incorrect - please try again...");
        Recaptcha.reload();
        return false;
    }
}
+3  A: 

You should be using a callback. check out this jQuery FAQ item on this.

The code does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined.

 getUrlStatus('getStatus.php', function(status) {
    alert(status);
 });


function getUrlStatus(url, callback) {
  $.ajax({
     url: url,
     complete: function(xhr) {
         callback(xhr.status);
     }
  });
}
Ólafur Waage
Also, if you're incurably lazy, you can just set async to false. Note that this will cause the UI to freeze during the call.
Anthony Mills
I think he wants to pause for a second between showing the success message to the user and posting the form.
joshperry
That's what I'm trying to do, pause for a second....
songdogtech
You will need a callback. Trust me, I've had this problem a few times.
Ólafur Waage
A: 

You could fake the delay by animating some benign property like the opacity from 1 to 1 over 1 second and on the completion callback submit your form...

$("#captchaStatus")
    .html("You got it right - I'm sending the email now....")
    .animate({opacity: 1.0}, 1000, "linear", function() {
        submitMyForm();
    });
joshperry
I'd like to be lazy and try this, but I can't get it to work. Looks like I should learn how to use a callback, as above?
songdogtech
A: 

The secret is non-jQuery JS function setTimeout. This will perform your operation 1 second later:

setTimeout(function() {
  $("#captchaStatus").html("You got it right - I'm sending the email now....");
}, 1000);
ndp
Can't get that to work, either. Actually blows by the text printed by `#captchastatus` even faster.
songdogtech