I'm trying to submit a form using ajax with Laravel 8.
But I got a 422 Unprocessable Content
error.
After several searches I saw that it is a validation error. But I don't understand why.
web.php
Route::post('/eligibility/check', [EligibilitiesController::class, 'getEligibility']);
EligibilitiesController.php
public function getEligibility(Request $request)
{
$request->validate([
'username' => 'required',
'email' => 'required'
]);
$data = $request->all();
return response()->json(['success'=>'Ajax request submitted successfully']);
}
index.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<form id="ajaxform">
@csrf
<input type="hidden" name="username" value="{{ $username }}">
<input type="hidden" name="email" value="{{ $email }}">
<button type="submit" >Send</button>
</form>
</body>
app.js
$(".save-data").click(function(event){
event.preventDefault();
let username = $("input[name=name]").val();
let email = $("input[name=email]").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/eligibility/check",
type:"POST",
data:{
username:username,
email:email
},
success:function(response){
console.log(response);
if(response) {
$('.success').text(response.success);
$("#ajaxform")[0].reset();
}
},
error: function(error) {
console.log("error:" error);
}
});
});
CodePudding user response:
Your input field for the username has the name 'username' and in your javascript you access 'name'.
So you have a validation error because no username is given.