views:

107

answers:

2

Hi, I'm trying to insert reCaptcha code into my page from jQuery, but it doesn't work.

Here is my code:

$("#button").click(function() {
        $("#loginBox").html($.getRecaptcha());
    })

When I try the following, my code doesn't even run. I think it's trying to execute instead of rendering it.

$.getRecaptcha = function(){
    return '<script type="text/javascript"' +
        'src="http://api.recaptcha.net/challenge?' + 
        'k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi"></script>';

}

With the following, the code runs, but when I click to #button I get an empty, full white browser window.

$.getRecaptcha = function(){
    var captcha = $("<script>")
        .attr("type", "text/javascript")
        .attr("src", "http://api.recaptcha.net/challenge?k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi");
    return captcha;
}

I don't want to insert reCaptcha code into my html from the beginning, because it downloads the reCaptcha content from the reCaptcha server even if my users don't want to use it. I could set the visibility of the container that holds the reCaptcha to invisible (display: none;), but it will dowload the content irrespectively of it.

I can insert the "noScript" code that reCaptcha gives us, but it doesn't work either, because it can spot that the browser allow javascript but I use noScript.

Any suggestions?

(I know I put my public reCaptcha key into the code, but it is just for testing purposes, and you could get it from my html or javascript code anyway)

UPDATE:

Krunal Mevada answered my question. But it doesn't work with reCaptcha. reCaptcha offers a reCaptcha AJAX API which is the answer to my specific question. However, with getScript() I can dinamically download the reCaptcha AJAX API javascipt file.

A: 

Use getScript method of jQuery.

May be this answer can be useful:

Stack Answer

Krunal
It does not work. When I do it this way I get the same result as the above mentioned in the 2. part. (blank, full white window)
Colby77
I found that this is a reCaptcha issue. They gives us a reCaptcha AJAX API which is the solution to my specific problem. However, your answer is the key, because now I can dinamically download the reCaptcha AJAX API javascript file, and whatever I want. Thank you. I've updated my question with these.
Colby77
A: 

First code part: insert a space at the end of the first line:

return '<script type="text/javascript" ' +

Hans