reCAPTCHA: Multiple callbacks doesn't work - javascript

I'm creating a login and signup system and to avoid bots, i'm using google recaptcha and i'm trying to use multiple callbacks to send form data to the server via ajax request and this appeared in console:
ReCAPTCHA couldn't find user-provided function: [object Object]
This is the code (the problem is in the line 4):
$(window).on('load',function(){
grecaptcha.render('recaptcha', {
'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
'callback' : {onSubmitLogin, onSubmitSignUp},
'size' : 'invisible'
});
});
//Login
$('#login').submit(function (e) {
e.preventDefault();
grecaptcha.execute();
}
);
function onSubmitLogin(token){
var formEmail = $('#email-login').val();
var formPasswd = $('#password-login').val();
var reCaptchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'account.php?action=login',
method: 'POST',
data: {formEmail, formPasswd, reCaptchaResponse},
dataType: 'json',
beforeSend: function() { $('#loading').fadeIn("slow"); },
complete: function() {
$('#loading').fadeOut("slow");
grecaptcha.reset();
},
success: function(response){
if(response.status == 'error'){
$('#alert-container').prepend('<div class="alert ' + response.status + ' showAlert"><div class="alert-content"><i class="fas fa-exclamation-circle"></i><p>' + response.message + '</p></div><button class="alert-close"><i class="fas fa-times"></i></button></div>');
}else if(response.status == 'success'){
window.location = "dashboard";
}
}
})
};
//SignUp
$('#signup').submit(function (e) {
e.preventDefault();
grecaptcha.execute();
}
);
function onSubmitSignUp(token){
var formEmail = $('#email-sign-up').val();
var formPasswd = $('#password-sign-up').val();
var formConfirmPasswd = $('#confirm-password-sign-up').val();
var reCaptchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'account.php?action=create',
method: 'POST',
data: {formEmail, formPasswd, formConfirmPasswd, reCaptchaResponse},
dataType: 'json',
beforeSend: function() { $('#loading').fadeIn("slow"); },
complete: function() {
$('#loading').fadeOut("slow");
grecaptcha.reset();
},
success: function(response){
$('#alert-container').prepend('<div class="alert ' + response.status + ' showAlert"><div class="alert-content"><i class="fas fa-exclamation-circle"></i><p>' + response.message + '</p></div><button class="alert-close"><i class="fas fa-times"></i></button></div>');
}
})
};

why don't you do something like this instead?
grecaptcha.render('recaptcha', {
'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
'callback' : () => {
onSubmitLogin();
onSubmitSignUp();
},
'size' : 'invisible'
});

Related

Set field Originator Signature to Current User

Good day, I have a SharePoint form the has a Originator Completed Dropdown with Yes or No as options. If the dropdown is yes, I would like to use JavaScript to set the OriginatorSignature (Text Field) to the loginName or current user. Can someone assist with this function?
<script src="/SiteAssets/jquery-3.2.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
GetUserLogin();
});
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
var loginName = data.d.LoginName.split('|')[1];
$("input[title='Originator Signature']").val(loginName);
}
function QueryError(error) {
alert(error);
}
</script>
The following code for your reference.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if($("select[title='Originator Completed Dropdown']").val()=="Yes"){
GetUserLogin();
}
$("select[title='Originator Completed Dropdown']").change(function(){
if($(this).val()=="Yes"){
GetUserLogin();
}else{
$("input[title='Originator Signature']").val("");
}
});
});
function GetUserLogin(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + _spPageContextInfo.userId + ")",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
var loginName = data.d.LoginName;
if(loginName.indexOf("|")!=-1){
loginName = loginName.split('|')[1];
}
$("input[title='Originator Signature']").val(loginName);
},
error: function (data) {
//alert("Error");
}
});
}
</script>

Checking Recaptcha still sends a message if false

There was a problem connecting Google Recaptcha v2. Or rather with the form. The check works fine, the error message displays, but, the message is still sent.
How can I fix this?
This is a form of feedback:
$(document).ready(function() {
$("#fast-call_submit").bind("click", function(e) {
e.preventDefault();
var form = $('#feedback_form');
var fields = form.serialize();
$.ajax({
url: form.attr('action') + '.json',
type: 'post',
data: fields,
dataType: 'json',
complete: function() {},
success: function(response) {
var v = grecaptcha.getResponse();
if (v.length == 0) {
$('.w-form-re-fail').show();
return false;
} else {
if (response.status == 'ok') {
$('.w-form-done').show();
$('.w-form-fail').hide();
form.hide();
} else {
$('.w-form-fail').show();
}
$('.w-form-re-fail').hide();
return true;
}
}
});
});
});

Button type button posting data is not saving in DB

i added on message Box and i am posting that data but not adding in my DB.
when i am trying to click Confirm button it is not saving in data-base how it will save to data-base can you please help me.
enter image description here
var leaveManagement= {
leaveData: null,
showModal: function(data) {
leaveManagement.leaveData = data;
$('#adminComment').val("");
$('#IsPaidLeave').prop('checked', false);
if ($(data).val() === "Reject") {
$(".form-check").hide();
} else {
var leaveTypeId = $(leaveManagement.leaveData).attr('data-leaveTypeId');
var userId = $(leaveManagement.leaveData).attr('data-employeeId');
if (leaveTypeId !== "" && leaveTypeId !== null && userId !== "" && userId !== null) {
$.ajax({
url: "/PayRoll/Leave/GetEmployeeLeaveTypeCount?employeeId=" +userId+"&leaveTypeId=" +leaveTypeId,
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#leaveCount').html('<span class="badge badge-outline badge-primary">Remaining Leave : '+data+'</span>');
},
error: function (e) {
}
});
}
$(".form-check").show();
}
$('#showCommentModal').modal('show');
},
changeRequest: function () {
if (leaveManagement.leaveData !== null) {
debugger;
var leaveId;
if ($(leaveManagement.leaveData).val() === "Approve") {
leaveId = $(leaveManagement.leaveData).attr('data-id');
leaveManagement.processRequest(leaveId, true, false);
} else if ($(leaveManagement.leaveData).val() === "Reject") {
leaveId = $(leaveManagement.leaveData).attr('data-id');
leaveManagement.processRequest(leaveId, false, true);
}
}
},
processRequest: function(leaveId, isApproved, isRejected) {
var comment = $('#adminComment').val();
var isPaidLeave = $('#IsPaidLeave').prop('checked');
$.ajax({
url: "/PayRoll/Leave/RespondToLeaveRequest/?leaveId=" +
leaveId +
"&isApproved=" +
isApproved +
"&IsRejected=" +
isRejected +
"&comment=" +
comment +
"&isPaidLeave=" +
isPaidLeave,
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (!data.success) {
$.notify(data.ResponseText, { position: "top right", className: "success" });
} else {
$.notify('Updated', { position: "top right", className: "success" });
}
$("#OpenLeaveRequestGrid").data('kendoGrid').dataSource.read();
$("#ClosedLeaveRequestGrid").data('kendoGrid').dataSource.read();
$('#adminComment').val("");
$('#IsPaidLeave').prop('checked', false);
$('#IsPaid').prop('checked', false);
},
error: function(data) {
console.log(data);
$.notify('Error', { position: "top right", className: "error" });
}
});
},
this is the button where if i click this button its should be save my comment data.
div class="modal-footer">
<button type="button" class="btn btn-warning" onclick="leaveManagement.changeRequest(this);" data-dismiss="modal" value="Confirm" id="bntconfirm">Confirm</button>#*<span class="fa fa-check"> Confirm</span>*#
</div>
this is the box where am writing comment.

How to apply changes to the current class in jQuery?

I've read similar questions and tried different methods, but nothing seems to work. I have a Liking system. A heart image which switches between liked (filled heart icon) and unliked (Plain bordered heart icon).
The problem is, when I click on the like/heart button, all the other records' heart icon turns to liked state. The same goes with the like count. When I like a post, all the post's like count becomes the same.
Also, I'm running an AJAX request to get the likes count. When I try to output the likes and increment/decrement if they like/unlike, the output is weird. It goes to -1 or 01 etc.
This is my main.blade.php :
<span class="activityLikes">
<input type="hidden" class="activityIdHidden" value="{{ $activity->activity_id }}">
<a class="likeBtn">
#if(Auth::user()->hasLikedActivity($activity))
<img class="likeImg likeTrue" src="IMG/icons/likeTrue.png" alt="likes">
#else
<img class="likeImg likeFalse" src="IMG/icons/like.png" alt="likes">
#endif
</a><span class="likesCount">{{ $activity->likes->count() }}</span>
</span>
This is my main.js file :
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
$('.likeImg').attr('src', 'IMG/icons/like.png');
$('.likesCount').text(likeCount - 1);
} else if(data == "liked"){
$('.likeImg').attr('src', 'IMG/icons/likeTrue.png');
$('.likesCount').text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
It is because you update every image that has the .likeImg class on the success event.
Can you try the following code ?
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
// element to update is `this` (the element that had been clicked)
var elementToUpdate = $(this).children('img');
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
elementToUpdate.attr('src', 'IMG/icons/like.png');
elementToUpdate.text(likeCount - 1);
} else if(data == "liked"){
elementToUpdate.attr('src', 'IMG/icons/likeTrue.png');
elementToUpdate.text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
You should chain your Ajax calls, and get the count after updating the "like" status, like this:
function errHandler(e) {
console.log(JSON.stringify("Exception: " + e));
}
$('.likeBtn').on('click', function(e){
var activityId = +$(this).siblings(".activityIdHidden").val(),
$img = $("img", this),
$likes = $(this).siblings(".likesCount");
e.preventDefault();
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
error: errHandler
}).then(function(data){
$img.attr('src', data === "deleted" ? 'IMG/icons/like.png' : 'IMG/icons/likeTrue.png');
return $.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
error: errHandler
});
}).then(function(data){
$likes.text(data);
});
});

Jquery replaceWith in a Foreach loop

When I execute the below code all the img with the id of imgg will be replaced because they are in a foreach loop, but I want to apply that to the clicked one only. Can any one help?
Html:
<button type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" style="width:100px;height:30px">
<p id="imgg">Add to Cart</p>
</button>
JS:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(imgg).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(imgg).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Thanks everyone i found the solution But you da real MVP, here it is
$(document).ready(function()
{
$(document).on('submit', '#reg-form', function()
{
var imgid = $(this).find("#imgg");
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type : 'POST',
url : '{{url("/ajax")}}',
data: {'name':data, '_token': $('input[name=_token]').val()},
success: function(data) {
$(imgid).replaceWith('<img id=imgg src=img/ajax.gif> ');
var thisForm = this;
setTimeout(function() {
$(imgg).replaceWith(' <p id=imgg>Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error : function(data)
{
alert("You must Login First");
}
});
return false;
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
Instead of using the $(imgg) use $(this), and you also missed the quotations when you where giving the id of iamge when you where using .replaceWith:
success: function(data) {
$(this).replaceWith('<img id="imgg" src="img/ajax.gif>" ');
var thisForm = this;
setTimeout(function() {
$(thisForm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
Reason?
Simple. The this object doesn't change. It is the owner of the function. See more about why here: Jquery - When to use "this" and when to use "$(this)"?
EDIT2
Now i have to put that in the upper level so this:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var vm = this //Upper Level
var data = $(this).find("#post_id").val();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(vm).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(vm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Please refer here about this particular problem:
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

Categories