Load reCAPTCHA dynamically - javascript

There are several ways to load reCAPTCHA using javascript such as below:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
This code load captcha on pageload. I want load reCAPTCHA just when clicked on "MYBTN". So the code changes into:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
});
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
But this code didn't work when I click on "MYBTN" and reCAPTCHA not load.
Help me plz. Thanks.

You just need to call loadCaptcha()
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
loadCaptcha(); // THIS LINE WAS MISSING
});
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>

Simple situation
Html
<input type="button" id="MYBTN" value="create captcha">
<div id="captcha_container"></div>
JS
var testSitekey = '6LeLzA4UAAAAANNRnB8kePzikGgmZ53aWQiruo7O';
$('#MYBTN').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': testSitekey
});
}, 1000);
});
Online demo (jsfiddle)

You just mentioned onload in your embedded script. Either you just remove onload from your embedded script or just keep your code outside of the onclick event in the function name loadCaptcha.
1. First Solution:
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
}
});
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
2. Second Solution
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
In first Solution your code will work when you click your button. Even you don't have to put then in loadCaptcha function you can directly call grecaptcha.render.
But when you mention onload in your script tag then it will not work according to your click then it will find the callback function you mentioned in the script. And as you wrote the loadCaptcha in onload of script and you wrote this function inside the onClick event. When the script tag executed, the code tried to find the loadCaptcha function which was not initialised till the script tag executed (as it would initialise on click event), So your script was not working.

JS
// Loading captcha with JavaScript on button click
jQuery(document).ready(function ($) {
$('#MYBTN').on('click',function() {
$.getScript( "https://www.google.com/recaptcha/api.js?render=__YOUR_KEY__" )
.done(function( script, textStatus ) {
if(typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
grecaptcha.execute('__YOUR_KEY__', {
action: 'homepage'
})
.then(function (token) {
var recaptchaResponse = document.getElementById('captcha_container');
recaptchaResponse.value = token;
});
// Your other code here
// You can control captcha badge here
});
}
});
});
});
HTML
// Required HTML:
<body>
<input type="button" id="MYBTN" value="MYBTN">
<div id="captcha_container"></div>
</body>

I've implemented the captcha to be loaded only after one of the required fields of my form was focus. I also implemented a check variable to see if the captcha's dependencies were inserted before.
Here is is:
jQuery('#MyRequiredInputId').focus(function () {
if(typeof loadedRecaptcha != 'undefined'){
return;
}
jQuery.getScript("https://www.google.com/recaptcha/api.js?render=___YOURKEY__")
.done(function (script, textStatus) {
if (typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
var siteKey = '___YOURKEY___';
jQuery('body').append(jQuery('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': siteKey
});
}, 1000);
});
}
loadedRecaptcha = true;
});
});
Note that in my case, I have a <div id= "captcha_container"></div> where I want to display my captcha.
Result:

I got the same issue today when I discovered that there are about 21 requests for Google Recaptcha even without open the login modal, this is indeed too much ):
After trying this method:
HTML
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div>
</div>
JS
<script>
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
finally, I get the results I want, now the recaptcha only loads when the login modal opens (based onClick function).
Unfortunately, I found that the main Google Recaptcha script still loads in console even while using the delay method mentioned above because the main script is declared on the page head:
<script src="https://www.google.com/recaptcha/api.js"></script>
So, I removed it from the page head then combined some lines of codes together to get it to work and only loads when the modal opens as follow:
Final code:
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div> //Wherever you want the reCaptcha to appear
</div>
<script>
//Add to the header or the footer it doesn't matter
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$.getScript("https://www.google.com/recaptcha/api.js") //The trick is here.
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
You can view it in action here:
https://youtu.be/dAZOSMR8iI8
Thank you

Tell Google you want to render the recaptcha explicitly (when you are ready). https://www.google.com/recaptcha/api.js?render=explicit
After the api script has run grecaptcha is available globally.
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<div id="whereIWantRecaptcha"></div>
<button id="myButton">show Recaptcha</button>
<script
src="https://www.google.com/recaptcha/api.js?render=explicit"
async
defer
></script>
<script>
var button = document.querySelector('#myButton');
button.addEventListener('click', function(){
grecaptcha.render('whereIWantRecaptcha', {
'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
});
});
</script>
</body>
</html>

Related

Change HTML structure according to JSON response from a REST API with JQuery

I have a REST API that returns a JSON object like this
{
"id": 1,
"status": "open"
}
where status can be "open" or "closed". I call this API in an HTML page with a JQuery function:
<html>
<body>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
If status from returned JSON object is "open", I want to change my HTML page as following
<html>
<body>
<p>THE QUESTION IS OPEN</p>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
Otherwise, if status from returned JSON object is "closed", I want to change my HTML page as following
<html>
<body>
<p>THE QUESTION IS CLOSED</p>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
What is the best way to achieve this with JQuery?
You can use $('body').prepend() to put the data right after the open <body> tag
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data) {
if (data.status) {
let str = `The Question is ${data.status}`.toUpperCase()
$('body').prepend(`<p>${str}</p>`)
}
});
});
// for the example
let data = {
"id": 1,
"status": "open"
}
if (data.status) {
let str = `The Question is ${data.status}`.toUpperCase()
$('body').prepend(`<p>${str}</p>`)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You have both id and status in your JSON object.
If you are going to have status paragraphs for several questions on the same page, this is the way you could do it:
$(document).ready(
function() {
$.getJSON("http://localhost:8080/api/question/1", function(data) {
let statusParagraph = document.getElementById("status-" + data.id);
let statusText;
if (data.status === "open") {
statusText = "THE QUESTION IS OPEN";
} else if (data.status === "closed") {
statusText = "THE QUESTION IS CLOSED";
}
statusParagraph.innerHTML = statusText;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<p id="status-1"></p>
<p id="status-2"></p>
</body>
</html>

JS, how can i refresh the page or div when json data changed?

Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);

How to include a php page through javascript and update it every so often? [duplicate]

I got this code from a website which I have modified to my needs:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<div id="links">
</div>
<script language="javascript" type="text/javascript">
var timeout = setTimeout(reloadChat, 5000);
function reloadChat () {
$('#links').load('test.php #links',function () {
$(this).unwrap();
timeout = setTimeout(reloadChat, 5000);
});
}
</script>
In test.php:
<?php echo 'test'; ?>
So I want test.php to be called every 5 seconds in links div. How can I do this right?
Try this out.
function loadlink(){
$('#links').load('test.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
Hope this helps.
Try using setInterval and include jquery library and just try removing unwrap()
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var timeout = setInterval(reloadChat, 5000);
function reloadChat () {
$('#links').load('test.php');
}
</script>
UPDATE
you are using a jquery old version so include the latest jquery version
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Try to not use setInterval.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
you can use this one.
<div id="test"></div>
you java script code should be like that.
setInterval(function(){
$('#test').load('test.php');
},5000);
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>

unable to load javascript in webview until refreshed

i have an html file called room.html.erb which has some js code.when i click on a link it has to load the above page.but the page is loading correctly except js code.when i refresh it working fine.
code in room.html.erb
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script>
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
</script>
i couldn't able to figure it out why it is happening.
Wait until the DOM is loaded?
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
});
</script>
another method
add
<div id="myPublisherDiv"></div>
<div id="subscribersDiv"></div>

Javascript not working in JQuery loaded DIV

I load pages into a div , my question is i cant execute javascript code in page1.php.. How can i execute code when i load page in to div.. thanks for your help..
here is my codes
index.php :
<script language="JavaScript" type="text/javascript">
function swapContent(cv) {
$("#content").html('<img class="loader" src="images/loader.gif"/>').show();
var url = "load.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#content").html(data).show();
});
}
</script>
Button1
Button2
<div id="content"></div>
load.php :
<?php
if(isset($_GET['contentVar']))
{
$contentVar = $_GET['contentVar'];
}else{
$contentVar = $_POST['contentVar']; }
if ($contentVar == "page1") {
include("page1.php");
} else if ($contentVar == "page2") {
include("page2.php");
}
and example for page1.php
<script type="text/javascript" src="nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
Data returned from Ajax is treated like plain text, so any Javascript within it is not executed by default. See this article.
Try using .load() instead of $.post() :
function swapContent(cv) {
$("#content").html('<img class="loader" src="images/loader.gif"/>').show();
var url = "load.php";
$("#content").load(url, {contentVar: cv});
}

Categories