Umbraco 7+ backoffice development, client actions - umbraco7

I am new in Umbraco Backoffice development. I just followed some tutorials about that. Now I am struggling because I don't understand the client model of Umbraco Backoffice. What I have done is the following view:
<div ng-controller="UmbExtend.UmbExtendTree.ImportController">
<div class="umb-pane">
<h1>Datei hochladen</h1>
<p>
Bitte laden sie die Datei hoch, welche importiert werden soll. Es sind nur CSV Dateien erlaubt.
</p>
<div class="umb-actions">
<input type="file" id="userImportFile"/>
</div>
<loading></loading>
<div class="btn-toolbar pull-right umb-btn-toolbar">
<a id="uploadNowButton" class="btn btn-primary" ng-click="runImport(99)" prevent-default>Benutzer jetzt importieren!</a>
</div>
</div>
</div>
<script>
function checkUserImportFile() {
var btn = $('#uploadNowButton');
if (!$('#userImportFile').val().trim().endsWith(".csv")) {
btn.addClass('disabled').fadeTo(500, 0);
} else {
btn.removeClass('disabled').fadeTo(500, 1);
}
}
$('#userImportFile').change(function () {
checkUserImportFile();
});
checkUserImportFile();
</script>
And the following client controller:
'use strict';
(function () {
//create the controller
function umbExtendImportController($scope, $routeParams, $http) {
//set a property on the scope equal to the current route id
$scope.id = $routeParams.id;
$scope.runImport = function () {
}
};
//register the controller
angular
.module("umbraco")
.controller('UmbExtend.UmbExtendTree.ImportController', umbExtendImportController);
})();
e.g. I want to hide the contextMenu on runImport click, where the view is shown. So how can I do that? Are there some examples or documentations for the client model of umbraco backoffice version 7+?

Here is the API documentation for the v7 back office: http://umbraco.github.io/Belle/#/api it's not complete, but it gives a good starting point.
As for hiding the context menu, I can't help you there, but the best advice I can give is to look at the back office source code here: https://github.com/umbraco/Umbraco-CMS/tree/dev-v7/src/Umbraco.Web.UI.Client and have a look at how things are done in the core code. That's usually my first port if call when I'm trying to do anything in the back office!

Inject the navigationService into your controller and use the hideNavigation() method like so:
function umbExtendImportController($scope, $routeParams, $http, navigationService) {
$scope.runImport = function () {
navigationService.hideNavigation();
}
};

Related

Getting response back from server but .html not sowing anything in wordpress ajax

On click I'm sending the id as data and then using query showing the name of user from WordPress database. I'm getting the response back from server but It is not adding when try to use .html(response).May be this is something to do with permission ?Like only admin can use the response?
If that's the case what I can do.
This is the ajax function:
function get_user_id() {
let get_current_user_id =jQuery(this).attr('id');
cur_user = '<?php echo get_current_user_id() ;?>';
var postdata_name = {action: "incoming_user_name_ajax_call",
param_user_to_chat: get_current_user_id,};
jQuery.post(ajaxurl, postdata_name, function (response) {
jQuery("#name-incoming-user").html(response);});
}
This is the function in functions.php
add_action("wp_ajax_incoming_user_name_ajax_call", "incoming_user_name_ajax_call_fn");
add_action("wp_ajax_nopriv_incoming_user_name_ajax_call", "incoming_user_name_ajax_call_fn");
function incoming_user_name_ajax_call_fn() {
global $wpdb;
$param_user_to_chat=isset($_REQUEST['param_user_to_chat'])?trim($_REQUEST['param_user_to_chat']):"";
if (!empty($param_user_to_chat)) {
$posts = $wpdb->get_results("SELECT distinct(display_name) FROM wp_users where
ID=$param_user_to_chat");
echo $posts[0]->display_name;
}
wp_die();}
Posting the HTML as well for everyone who want to know what jQuery(this).attr('id'); is doing. It is getting id "4" or "2" depending on click.
<div id="target">
<div class="user-list-hide" id="user-hide" style="display: block;">
<div id="4"><span>Jason Bradley</span>/div>
<div id="2"><span>John Saddington</span></div>
</div>
</div>
There was issue in your jquery code i.e : the way you were calling your get_user_id() function here you have use wrong selector to get your inner divs . So, to make it work change :
jQuery("#target").on("click", "div", get_user_id);
to
jQuery("#user-hide").on("click", "div", get_user_id);

How to show data of a single id using Vue js?

I'm displaying all records on a page at this URI xxx.test/employer/search/filter-by. I'm using Algolia Search to display all of the records/results. I added a button called View Profile and attached an empty method to it called showProfile.
When a user clicks on this button, I want to display this specific profile/record on a new page by itself. If I was fetching data on my own, i.e. without Algolia's code I would be able to do this, but in this case I'm not really sure how to do this.
EmployerSearchComponent.vue:
<ais-instant-search
:search-client="searchClient"
index-name="candidate_profiles"
>
<ais-search-box v-model="query" class="mb-3" placeholder="Search by job title, company name or city..." />
<ais-configure
:restrictSearchableAttributes="['job_title', 'employment_type']"
:hitsPerPage="25"
/>
<b-row class="job-search-card">
<ais-hits class="w-100">
<template slot="item" slot-scope="{ item }">
<b-col cols="12" class="mb-3">
<b-card>
<div class="float-right">
<i class="flaticon-paper-plane"></i> View Profile
</div>
<h4 style="margin-bottom: 20px;"><router-link to="/">{{item.job_title}}</router-link></h4>
<p>Type: {{item.employment_type}}</p>
<b-card-text class="mt-2"><span v-if="item.experience && item.experience.length < 300">{{item.experience}}</span><span v-else>{{item.experience && item.experience.substring(0,300)+"..."}}</span></b-card-text>
</b-card>
</b-col>
</template>
</ais-hits>
<ais-pagination />
</b-row>
</ais-instant-search>
If I click on the network tab in the console, and on the algolia query search URI, I can see that the search results are in results[0].hits. Below is a screenshot of this data.
P.S. My data is empty it just contains algolia client ID's.
How can I display a single id on a new page? I understand that I need to get the id from the record that is being displayed, and show this information on a new page, but I don't know how to put it all together.
Again I think I'll need a route, so I created this
Route::get('/employer/search/filter-by/show/{id}', 'EmployerSearchController#show')->name('employer.search.show');
I'm using Laravel for my backend. Thanks in advance.
------------------------------------- UPDATED: -------------------------------------
I feel like I'm really close, but $itemId in my controller after I die and dump returns "undefined" for some reason.
router.js (Vue Router):
{
path: '/employer/search/filter-by/:itemId/show',
name: 'employer-search-index',
component: SearchIndex,
meta: {
breadcrumb: 'Search Candidates',
requiresAuthEmployer: true,
employerHasPaid: true
},
},
EmployerSearchComponent.vue - with the <router-link> button:
<template slot="item" slot-scope="{ item }">
<b-col cols="12" class="mb-3">
<b-card>
<div class="float-right">
<router-link class="apply-job-btn btn btn-radius theme-btn apply-it" :to="'/employer/search/filter-by/' + item.id + '/show'">View Profile</router-link>
</div>
<h4 style="margin-bottom: 20px;"><router-link to="/">{{item.job_title}}</router-link></h4>
<p>Type: {{item.employment_type}}</p>
<b-card-text class="mt-2"><span v-if="item.experience && item.experience.length < 300">{{item.experience}}</span><span v-else>{{item.experience && item.experience.substring(0,300)+"..."}}</span></b-card-text>
</b-card>
</b-col>
</template>
EmployerSearchController.php:
public function show ($itemId)
{
$candidateProfiles = CandidateProfile::with(['user', 'photo', 'resume', 'video'])
->where('id', '=', $itemId)->get();
return Response::json(array(
'candidateProfiles' => $candidateProfiles,
), 200);
}
api.php:
Route::get('/employer/search/filter-by/{itemId}/show', 'EmployerSearchController#show')->name('employer.search.show');
And Finally, in the .vue file that shows the Full Single Profile, I'm loading the data like this.
mounted() {
this.loadCandidateProfileData();
},
methods: {
loadCandidateProfileData: async function () {
try {
const response = await employerService.loadCandidateProfileData();
this.candidateProfiles = response.data.candidateProfiles;
} catch (error) {
this.$toast.error("Some error occurred, please refresh!");
}
},
}
And the employerService.js file from the above code:
export function loadCandidateProfileData(itemId, data) {
return http().get(`employer/search/filter-by/${itemId}/show`, data);
}
As you suggest, you'll need an API endpoint to fetch the data from, returning it as a JSON object. You'll need to add a route to your client-side routes that takes the job ID (or slug) as a parameter. In your job component, you can retrieve the route param (e.g. in the created() method) as $route.params.id, for example, and use that to fetch the data from your API.
If your Algolia search is returning all the data that you want to display on your single job listing page, you could just put that in your Vuex store and display it without having to make another HTTP request. The downside of that would be that if a user bookmarked the page to return to later, there'd be no data in the store to display.
Thank you to Nilson Jacques responses. If you follow our conversation.
Finally I got the itemId param from the route and passed it to loadCandidateProfileData() like this:
loadCandidateProfileData: async function() {
try {
const itemId = this.$route.params.itemId;
const response = await employerService.loadCandidateProfileData(itemId);
this.candidateProfiles = response.data.candidateProfiles;
console.log(this.candidateProfiles);
if (response.data.candidateProfiles.current_page < response.data.candidateProfiles.last_page) {
this.moreExists = true;
this.nextPage = response.data.candidateProfiles.current_page + 1;
} else {
this.moreExists = false;
}
} catch (error) {
this.$toast.error("Some error occurred, please refresh!");
}
},

Updating the DOM with change in an object (vue.js) - binding not working?

I have the app.js file where gmarkers is an array of objects :
var vm = new Vue({
el: '#lili',
data: {
listings: gmarkers
}
});
In my HTML file :
<div id="lili" >
<div
v-repeat="gmarker : listings"
class="listing listing-list col-sm-12"
style="height:50px;line-height:50px;"
data-cat="#{{gmarker.mycategory}}"
data-id="#{{gmarker.id}}"
>
<span style="color:black;">
<a target="_blank" href="#{{gmarker.listlink}}">
#{{ gmarker.listname }}
</a>
</span>
<span class="tag blue-back" style="margin-left:5px;">
<a target="_blank" href="#{{gmarker.catlink}}">
#{{gmarker.listcat}}
</a>
</span>
<span style="margin-left:20px;color:#bbb;">
#{{gmarker.distance}}km
</span>
</div>
</div>
When loading the page, the DOM loads correctly, displaying the list I'm looking for but when (after an ajax call in js) the gmarkers object changes, the DOM doesn't change.
The new gmarkers is totally created from scratch and containing new objects.
What am I missing ?
It sound like you are wrong about what data is being bound here. You are expecting data: {listings: gmarkers} to do binding between vm.listings and the gmarkers array. This isn't what it does. It copies the gmarkers data into the listings and doesn't listen to gmarkers anymore. See this fiddle for an example of what I think you are doing wrong.
We can fix the above fiddle by setting the vm.listings to the new array of objects after the ajax request.
vm.$set('listings', gmarkers);
You can see this in action in this updated fiddle.
It is actually pretty common to see a blank listings until ajax returns them. Here is some sample code that will call an ajax request when vue is ready and update the listings once it is finished. Note: this exampe uses vue-resources to perform the ajax request. You may not have this. You can always just use jQuery or javascript to perform this.
data: {
listings: []
},
ready: function () {
this.fetchListings();
},
methods: {
fetchListings: function () {
this.$http.get('/your/api/listings', function (response) {
this.$set('listings', response);
});
}
}
This fiddle shows the above code but pay attention to the differences required for the fake ajax request I used.

CakePHP 1.3 - Send non-form data to controller with js helper

I have a ul of dynamic buttons in my view that appears like the following:
<ul id="dashboard_list">
<li id="id_100" class="btn btn-primary">
<a id="id_100" href="/plugin_name/controller_name/action_name/100">Default View</a>
</li>
<li id="id_200" class="btn btn-primary">
<a id="id_200" href="/plugin_name/controller_name/action_name/200">Second View</a>
</li>
<li id="id_300" class="btn btn-primary">
<a id="id_300" href="/plugin_name/controller_name/action_name/300">Third View</a>
</li>
</ul>
The above links are created using the JSHelper as follows:
echo $this->Html->link($view->name, '/plugin_name/controller_name/action_name/'. $view->id, array('class' => 'ajax-link', 'id'=> $view->id));
I'm using the script below that I found while researching:
// onClick function
function onClick(){
$('#view_container').load($(this).attr('href'), onSuccess);
return false;
}
// activate ajax links to call the onClick function
$('.ajax-link').live('click', onClick);
// onSuccess-callback function
function onSuccess(){}
Now, in my controller / action im doing a simple check for data as follows:
function actionName() {
if ($this->data != null) {
die('We has data!');
}
else
{
die('We has no data.');
}
}
My #view_container element updates properly with "We has no data" on every click. So, I'm obviously not communicating the link's view id number (data) between the view and the controller.
Can anyone offer some direction on how to implement this functionality in CakePHP 1.3 to access the selected id (variable) in the controller? I mostly seem to find form submission examples (or just dead links), and I unfortunately don't have the option to upgrade cakePHP.
FYI: The proper helpers, scripts and the js->writeBuffer are being included.
Thank you for any responses in advance!
Rewrite your function as follows:
function actionName($id) {
debug($id);
if ($this->data != null) {
die('We has data!');
}
else
{
die('We has no data.');
}
}
If you need to do more than one variable in the URL ex:
href="/plugin_name/controller_name/action_name/300/yellow/bannana"
Then your function would look like:
function actionName($id,$color,$fruit) {
}

How do I show multiple recaptchas on a single page?

I have 2 forms on a single page. One of the forms has a Recaptcha displaying all the time. The other should display a Recaptcha only after a certain event such as maxing out login attempts. So there are times when I would need 2 Recaptchas to appear on the same page. Is this possible? I know I could probably use a single one for both, but the way I have the layout, I would much prefer to have 2. Thanks.
Update: well I guess it may not be possible. Can anybody recommend another capture library to use side by side with reCaptcha? I really want to be able to have 2 captchas on the same page.
Update 2: What if I put each form in an iframe? Would this be an acceptable solution?
With the current version of Recaptcha (reCAPTCHA API version 2.0), you can have multiple Recaptchas on one page.
There is no need to clone the Recaptcha nor try to workaround the problem. You just have to put multiple <div> elements for the Recaptchas and render the Recaptchas inside them explicitly.
This is easy with the Google Recaptcha API. Here is the example HTML code:
<form>
<h1>Form 1</h1>
<div><input type="text" name="field1" placeholder="field1"></div>
<div><input type="text" name="field2" placeholder="field2"></div>
<div id="RecaptchaField1"></div>
<div><input type="submit"></div>
</form>
<form>
<h1>Form 2</h1>
<div><input type="text" name="field3" placeholder="field3"></div>
<div><input type="text" name="field4" placeholder="field4"></div>
<div id="RecaptchaField2"></div>
<div><input type="submit"></div>
</form>
In your Javascript code, you have to define a callback function for Recaptcha:
<script type="text/javascript">
var CaptchaCallback = function() {
grecaptcha.render('RecaptchaField1', {'sitekey' : '6Lc_your_site_key'});
grecaptcha.render('RecaptchaField2', {'sitekey' : '6Lc_your_site_key'});
};
</script>
After this, your Recaptcha script URL should look like this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
Or instead of giving IDs to your Recaptcha fields, you can give a class name and loop these elements with your class selector and call .render().
Simple and straightforward:
Create your Recaptcha fields normally with this:
<div class="g-recaptcha" data-sitekey="YOUR_KEY_HERE"></div>
Load the script with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
Now call this to iterate over the fields and create the Recaptchas:
<script type="text/javascript">
var CaptchaCallback = function() {
jQuery('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {
'sitekey' : jQuery(el).attr('data-sitekey')
,'theme' : jQuery(el).attr('data-theme')
,'size' : jQuery(el).attr('data-size')
,'tabindex' : jQuery(el).attr('data-tabindex')
,'callback' : jQuery(el).attr('data-callback')
,'expired-callback' : jQuery(el).attr('data-expired-callback')
,'error-callback' : jQuery(el).attr('data-error-callback')
});
});
};
</script>
This answer is an extension to #raphadko's answer.
If you need to extract manually the captcha code (like in ajax requests) you have to call:
grecaptcha.getResponse(widget_id)
But how can you retrieve the widget id parameter?
I use this definition of CaptchaCallback to store the widget id of each g-recaptcha box (as an HTML data attribute):
var CaptchaCallback = function() {
jQuery('.g-recaptcha').each(function(index, el) {
var widgetId = grecaptcha.render(el, {'sitekey' : 'your code'});
jQuery(this).attr('data-widget-id', widgetId);
});
};
Then I can call:
grecaptcha.getResponse(jQuery('#your_recaptcha_box_id').attr('data-widget-id'));
to extract the code.
A similar question was asked about doing this on an ASP page (link) and the consensus over there was that it was not possible to do with recaptcha. It seems that multiple forms on a single page must share the captcha, unless you're willing to use a different captcha. If you are not locked into recaptcha a good library to take a look at is the Zend Frameworks Zend_Captcha component (link). It contains a few
This is easily accomplished with jQuery's clone() function.
So you must create two wrapper divs for the recaptcha. My first form's recaptcha div:
<div id="myrecap">
<?php
require_once('recaptchalib.php');
$publickey = "XXXXXXXXXXX-XXXXXXXXXXX";
echo recaptcha_get_html($publickey);
?>
</div>
The second form's div is empty (different ID). So mine is just:
<div id="myraterecap"></div>
Then the javascript is quite simple:
$(document).ready(function() {
// Duplicate our reCapcha
$('#myraterecap').html($('#myrecap').clone(true,true));
});
Probably don't need the second parameter with a true value in clone(), but doesn't hurt to have it... The only issue with this method is if you are submitting your form via ajax, the problem is that you have two elements that have the same name and you must me a bit more clever with the way you capture that correct element's values (the two ids for reCaptcha elements are #recaptcha_response_field and #recaptcha_challenge_field just in case someone needs them)
I know this question is old but in case if anyone will look for it in the future. It is possible to have two captcha's on one page. Pink to documentation is here: https://developers.google.com/recaptcha/docs/display
Example below is just a copy form doc and you dont have to specify different layouts.
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
The grecaptcha.getResponse() method accepts an optional "widget_id" parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created, it is not related to the attribute id of the reCAPTCHA container!!
Each reCAPTCHA has its own response data.
You have to give the reCAPTCHA div an ID and pass it to the getResponse method:
e.g.
<div id="reCaptchaLogin"
class="g-recaptcha required-entry"
data-sitekey="<?php echo $this->helper('recaptcha')->getKey(); ?>"
data-theme="<?php echo($this->helper('recaptcha')->getTheme()); ?>"
style="transform:scale(0.82);-webkit-transform:scale(0.82);transform-origin:0 0;-webkit-transform-origin:0 0;">
</div>
<script type="text/javascript">
var CaptchaCallback = function() {
jQuery('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {
'sitekey' : jQuery(el).attr('data-sitekey')
,'theme' : jQuery(el).attr('data-theme')
,'size' : jQuery(el).attr('data-size')
,'tabindex' : jQuery(el).attr('data-tabindex')
,'callback' : jQuery(el).attr('data-callback')
,'expired-callback' : jQuery(el).attr('data-expired-callback')
,'error-callback' : jQuery(el).attr('data-error-callback')
});
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
Access response:
var reCaptchaResponse = grecaptcha.getResponse(0);
or
var reCaptchaResponse = grecaptcha.getResponse(1);
I have contact form in footer that always displays and also some pages, like Create Account, can have captcha too, so it's dynamically and I'm using next way with jQuery:
html:
<div class="g-recaptcha" id="g-recaptcha"></div>
<div class="g-recaptcha" id="g-recaptcha-footer"></div>
javascript
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit&hl=en"></script>
<script type="text/javascript">
var CaptchaCallback = function(){
$('.g-recaptcha').each(function(){
grecaptcha.render(this,{'sitekey' : 'your_site_key'});
})
};
</script>
This is a JQuery-free version of the answer provided by raphadko and noun.
1) Create your recaptcha fields normally with this:
<div class="g-recaptcha"></div>
2) Load the script with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
3) Now call this to iterate over the fields and create the recaptchas:
var CaptchaCallback = function() {
var captchas = document.getElementsByClassName("g-recaptcha");
for(var i = 0; i < captchas.length; i++) {
grecaptcha.render(captchas[i], {'sitekey' : 'YOUR_KEY_HERE'});
}
};
Looking at the source code of the page I took the reCaptcha part and changed the code a bit. Here's the code:
HTML:
<div class="tabs">
<ul class="product-tabs">
<li id="product_tabs_new" class="active">Detailed Description</li>
<li id="product_tabs_what">Request Information</li>
<li id="product_tabs_wha">Make Offer</li>
</ul>
</div>
<div class="tab_content">
<li class="wide">
<div id="product_tabs_new_contents">
<?php $_description = $this->getProduct()->getDescription(); ?>
<?php if ($_description): ?>
<div class="std">
<h2><?php echo $this->__('Details') ?></h2>
<?php echo $this->helper('catalog/output')->productAttribute($this->getProduct(), $_description, 'description') ?>
</div>
<?php endif; ?>
</div>
</li>
<li class="wide">
<label for="recaptcha">Captcha</label>
<div id="more_info_recaptcha_box" class="input-box more_info_recaptcha_box"></div>
</li>
<li class="wide">
<label for="recaptcha">Captcha</label>
<div id="make_offer_recaptcha_box" class="input-box make_offer_recaptcha_box"></div>
</li>
</div>
jQuery:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
var recapExist = false;
// Create our reCaptcha as needed
jQuery('#product_tabs_what').click(function() {
if(recapExist == false) {
Recaptcha.create("<?php echo $publickey; ?>", "more_info_recaptcha_box");
recapExist = "make_offer_recaptcha_box";
} else if(recapExist == 'more_info_recaptcha_box') {
Recaptcha.destroy(); // Don't really need this, but it's the proper way
Recaptcha.create("<?php echo $publickey; ?>", "more_info_recaptcha_box");
recapExist = "make_offer_recaptcha_box";
}
});
jQuery('#product_tabs_wha').click(function() {
if(recapExist == false) {
Recaptcha.create("<?php echo $publickey; ?>", "make_offer_recaptcha_box");
recapExist = "more_info_recaptcha_box";
} else if(recapExist == 'make_offer_recaptcha_box') {
Recaptcha.destroy(); // Don't really need this, but it's the proper way (I think :)
Recaptcha.create("<?php echo $publickey; ?>", "make_offer_recaptcha_box");
recapExist = "more_info_recaptcha_box";
}
});
});
</script>
I am using here simple javascript tab functionality. So, didn't included that code.
When user would click on "Request Information" (#product_tabs_what) then JS will check if recapExist is false or has some value. If it has a value then this will call Recaptcha.destroy(); to destroy the old loaded reCaptcha and will recreate it for this tab. Otherwise this will just create a reCaptcha and will place into the #more_info_recaptcha_box div. Same as for "Make Offer" #product_tabs_wha tab.
var ReCaptchaCallback = function() {
$('.g-recaptcha').each(function(){
var el = $(this);
grecaptcha.render(el.get(0), {'sitekey' : el.data("sitekey")});
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallback&render=explicit" async defer></script>
ReCaptcha 1
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>
ReCaptcha 2
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>
ReCaptcha 3
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>
To add a bit to raphadko's answer: since you have multiple captchas (on one page), you can't use the (universal) g-recaptcha-response POST parameter (because it holds only one captcha's response). Instead, you should use grecaptcha.getResponse(opt_widget_id) call for each captcha. Here's my code (provided each captcha is inside its form):
HTML:
<form ... />
<div id="RecaptchaField1"></div>
<div class="field">
<input type="hidden" name="grecaptcha" id="grecaptcha" />
</div>
</form>
and
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
JavaScript:
var CaptchaCallback = function(){
var widgetId;
$('[id^=RecaptchaField]').each(function(index, el) {
widgetId = grecaptcha.render(el.id, {'sitekey' : 'your_site_key'});
$(el).closest("form").submit(function( event ) {
this.grecaptcha.value = "{\"" + index + "\" => \"" + grecaptcha.getResponse(widgetId) + "\"}"
});
});
};
Notice that I apply the event delegation (see refresh DOM after append element ) to all the dynamically modified elements. This binds every individual captha's response to its form submit event.
A good option is to generate a recaptcha input for each form on the fly (I've done it with two but you could probably do three or more forms). I'm using jQuery, jQuery validation, and jQuery form plugin to post the form via AJAX, along with the Recaptcha AJAX API -
https://developers.google.com/recaptcha/docs/display#recaptcha_methods
When the user submits one of the forms:
intercept the submission - I used jQuery Form Plugin's beforeSubmit property
destroy any existing recaptcha inputs on the page - I used jQuery's $.empty() method and Recaptcha.destroy()
call Recaptcha.create() to create a recaptcha field for the specific form
return false.
Then, they can fill out the recaptcha and re-submit the form. If they decide to submit a different form instead, well, your code checks for existing recaptchas so you'll only have one recaptcha on the page at a time.
Here's a solution that builds off many of the excellent answers. This option is jQuery free, and dynamic, not requiring you to specifically target elements by id.
1) Add your reCAPTCHA markup as you normally would:
<div class="g-recaptcha" data-sitekey="YOUR_KEY_HERE"></div>
2) Add the following into the document. It will work in any browser that supports the querySelectorAll API
<script src="https://www.google.com/recaptcha/api.js?onload=renderRecaptchas&render=explicit" async defer></script>
<script>
window.renderRecaptchas = function() {
var recaptchas = document.querySelectorAll('.g-recaptcha');
for (var i = 0; i < recaptchas.length; i++) {
grecaptcha.render(recaptchas[i], {
sitekey: recaptchas[i].getAttribute('data-sitekey')
});
}
}
</script>
It is possible, just overwrite the Recaptcha Ajax callbacks. Working jsfiddle: http://jsfiddle.net/Vanit/Qu6kn/
You don't even need a proxy div because with the overwrites the DOM code won't execute. Call Recaptcha.reload() whenever you want to trigger the callbacks again.
function doSomething(challenge){
$(':input[name=recaptcha_challenge_field]').val(challenge);
$('img.recaptcha').attr('src', '//www.google.com/recaptcha/api/image?c='+challenge);
}
//Called on Recaptcha.reload()
Recaptcha.finish_reload = function(challenge,b,c){
doSomething(challenge);
}
//Called on page load
Recaptcha.challenge_callback = function(){
doSomething(RecaptchaState.challenge)
}
Recaptcha.create("YOUR_PUBLIC_KEY");
Here is a nice guide for doing exactly that:
http://mycodde.blogspot.com.ar/2014/12/multiple-recaptcha-demo-same-page.html
Basically you add some parameters to the api call and manually render each recaptcha:
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
<script>
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
//Render the recaptcha1 on the element with ID "recaptcha1"
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : '6Lc_0f4SAAAAAF9ZA', //Replace this with your Site key
'theme' : 'light'
});
//Render the recaptcha2 on the element with ID "recaptcha2"
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : '6Lc_0f4SAAAAAF9ZA', //Replace this with your Site key
'theme' : 'dark'
});
};
</script>
PS: The "grecaptcha.render" method receives an ID
I would use invisible recaptcha. Then on your button use a tag like " formname='yourformname' " to specify which form is to be submitted and hide a submit form input.
The advantage of this is it allows for you to keep the html5 form validation intact, one recaptcha, but multiple button interfaces. Just capture the "captcha" input value for the token key generated by recaptcha.
<script src="https://www.google.com/recaptcha/api.js" async defer ></script>
<div class="g-recaptcha" data-sitekey="yours" data-callback="onSubmit" data-size="invisible"></div>
<script>
var formanme = ''
$('button').on('click', function () { formname = '#'+$(this).attr('formname');
if ( $(formname)[0].checkValidity() == true) { grecaptcha.execute(); }
else { $(formname).find('input[type="submit"]').click() }
});
var onSubmit = function(token) {
$(formname).append("<input type='hidden' name='captcha' value='"+token+"' />");
$(formname).find('input[type="submit"]').click()
};
</script>
I find this FAR simpler and easier to manage.

Resources