14 September 2012
sometimes, you want to do lightbox for Email Us or Contact Us page.
in this case, you don't want to include the recaptcha js in every page, you want to include it in the popup lightbox but here we have an issue that $(document).ready would be called while the google recaptcha js is not loaded. b/c document ready is just checking the original page instead of the lightbox. in this case, here is a common solution for every js loading (wait until that js loaded.)

<script type="text/javascript" src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var reCaptcha_timer;
        reCaptcha_timer = setInterval(function(){
          if (typeof(Recaptcha) != 'undefined') {
             clearInterval(reCaptcha_timer);
             CreateReCaptcha();
          }
        }, 50);
    });
    function CreateReCaptcha() {
        Recaptcha.create("public_key_blabla", 'captcha-placeholder', {
            theme: "white",
            callback: Recaptcha.focus_response_field
        });
    }
</script>

see we have a tricky that keep check if Recaptcha is inited (which will be done when recatpcha_ajax.js is loaded).
and only after it's loaded, we clear the check, and create the catpcha.

the trick works pretty good. but here is another issue, when the lightbox is loaded and user submits the form, and if some elements are wrong or captcha is wrong, that we need show captcha once again. it will be broken. b/c Recaptcha js variable is already defined, and Recaptcha.create will not working fine b/c it has something stored for previous captcha.

in this case, another tricky is much more simpler.

<script type="text/javascript">
// so that we can reload it
if (typeof(Recaptcha) != 'undefined') Recaptcha = undefined;
</script>
<script type="text/javascript" src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>

before load the js, we reset it so it works like it's the first time we are trying to create reCaptcha.

those issue only happens on ajax lightbox load reCaptcha and ajaxPost the reCaptcha form.
stupid but works.

Thanks.


blog comments powered by Disqus