Domanda

Devo mettere un ritardo di un secondo in questa funzione jQuery in modo che quando il captcha è compilato correttamente, ci sia un ritardo sufficiente (un secondo, credo) per mostrare #captchaStatus prima del passaggio successivo del processo (che è un html pubblicato).

Deve essere abbastanza semplice, anche se sto imparando jQuery .... Idee? Grazie.

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;
    }
}
È stato utile?

Soluzione

Dovresti usare un callback. controlla questa domanda frequente su questo argomento

  

Il codice non funziona come desiderato a causa della natura della programmazione asincrona. Il gestore del successo fornito non viene richiamato immediatamente, ma piuttosto in futuro in caso di risposta dal server. Quindi quando usiamo la variabile 'status' immediatamente dopo la chiamata $ .ajax, il suo valore è ancora indefinito.

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


function getUrlStatus(url, callback) {
  $.ajax({
     url: url,
     complete: function(xhr) {
         callback(xhr.status);
     }
  });
}

Altri suggerimenti

Potresti fingere il ritardo animando alcune proprietà benigne come l'opacità da 1 a 1 in 1 secondo e al termine del callback invia il tuo modulo ...

$("#captchaStatus")
    .html("You got it right - I'm sending the email now....")
    .animate({opacity: 1.0}, 1000, "linear", function() {
        submitMyForm();
    });

Il segreto è setTimeout non JQuery JS. Ciò eseguirà l'operazione 1 secondo più tardi:

setTimeout(function() {
  $("#captchaStatus").html("You got it right - I'm sending the email now....");
}, 1000);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top