Reputation: 125
how can I send my form using AJAX with recaptcha? I'm currently using the package from anhskohbo/no-captcha.
SignupController.php
public function customRegister(Request $request) {
$validator = Validator::make($request->all(), [
'name' => ['required', 'max:52'],
'phone_number' => ['required', 'unique:users', 'min:11', 'max:11'],
'password' => ['required', 'confirmed',
Password::min(8)
->mixedCase()
->symbols()
->numbers()
],
'g-recaptcha-response' => ['required', 'captcha'],
]);
if(!$validator->passes()) {
return response()->json(['status' => 0, 'error'=> $validator->errors()->toArray()]);
} else {
User::create([
'name' => $request->input('name'),
'phone_number' => $request->input('phone_number'),
'password' => Hash::make($request->input('password')),
'is_verified' => 0,
]);
}
Form.blade
<form action="/register" id="registerForm" method="POST">
@csrf
... form inputs here
<div class="form-group fxt-transformY-50 fxt-transition-delay-5">
<div class="{{ $errors->has('g-recaptcha-response') ? ' has-error' : '' }} recaptcha-div">
{!! NoCaptcha::display() !!}
<span class="text-danger error-text g-recaptcha-response_error"></span>
</div>
</div>
</form>
My Ajax function
$(function(){
$("#registerForm").on('submit', function(e){
e.preventDefault();
var token = grecaptcha.getResponse();
$.ajax({
url:$(this).attr('action'),
method:$(this).attr('method'),
data: new FormData(this),
processData:false,
dataType:'json',
contentType:false,
beforeSend:function(){
$(document).find('span.error-text').text('');
FormData.append('recaptcha', token);
},
success:function(data){
if(data.status == 0){
$.each(data.error, function(prefix, val){
$('span.'+prefix+'_error').text(val[0]);
});
}else{
$('#registerForm')[0].reset();
alert(data.msg);
}
}
});
});
});
I always get the following error 'recaptcha is required'. It seems that the formData is not getting the recaptcha value. Can anyone give me advice? Thank you!
Upvotes: 2
Views: 2582
Reputation: 71
How it work for me
In form
<div class="g-recaptcha" data-sitekey="{{config('services.recaptcha.key')}}"></div>
Script recaptcha
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Ajax function
$("#registerForm").on('submit', function(e){
e.preventDefault();
var gtoken = grecaptcha.getResponse();
$.ajax({
...
data: {
g_recaptcha_response: gtoken,
},
In validation request
'g_recaptcha_response' => 'required|recaptcha'
Upvotes: 3