Answer the question
In order to leave comments, you need to log in
Why is the promise not working?
Hello!
There is a googlecaptcha promise v3. On submit on the form, the function to get the captcha token is called, assigned to the input and sent. The problem is that when you click Send for the first time, the token is assigned, but it is not transferred in the post array, so the validation error and sending does not occur. If you immediately click a second time, the token in the input will change and the form will submit.
1. Why does the assigned input value not get into the post on the first click?
2. Why is the form submitted when clicking Submit again, although the input token changes to a new one?
The code itself
$('.js-bottom-form').submit(function(e){
e.preventDefault();
var formData = new FormData($('#bottom-form')[0]);
var $self = $(this).first();
var preloader = $(this).siblings('.form-preloader');
var inputName = $(this).find('input[name="name"]');
var inputPhone = $(this).find('input[name="phone"]');
var name = inputName.val();
var phone = inputPhone.val();
grecaptcha.ready(function () {
grecaptcha.execute('6LcXhlobAAAAAMj4rKvycKxrahQM9ycMn1n7bf0k', { action: 'submit' })
.then(function (token) {
$($self).find('input.recaptchaResponse').val(token);
console.log(token);
})
.then(() => {
console.log('готово');
if (name.length < 2) {
inputName.addClass('error');
return false;
} else {
inputName.removeClass();
}
if (phone.length != 18) {
inputPhone.addClass('error');
return false;
} else {
inputPhone.removeClass();
}
$.ajax({
url: $self.attr('action'),
type: 'POST',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $self.data('token'),
},
data:formData,
cache:false,
contentType: false,
processData: false,
beforeSend: function() {
console.log(formData);
preloader.show();
$(this).find('input[type=submit]').prop('disabled', true);
},
complete: function() {
preloader.hide();
}
})
.done(function(data) {
console.log(data);
if (data['status']) {
$self.find('.form__content').html('Специалист свяжется с Вами в течение 15 мин.<br><br>');
} else {
console.log(data);
}
console.log("success");
})
.fail(function(data) {
})
.always(function() {
});
});
});
});
Answer the question
In order to leave comments, you need to log in
var formData
for sending is generated from the form immediately when you click send - at this time, the captcha token has not yet been received. Adding it to the form fields no longer affects the previously generated formData.
It also sucks that the validation of the entered data is done only after the captcha.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question