I've been stuck with this for hours, checked dozens of examples / StackOverflow answers but I am still getting the same error. It's my first time working with AJAX, but I have a solid amount of experience with Laravel.
The issue I'm getting is a 500 Internal Server Error when trying to send my AJAX request, the aim of which is to update a single row in my database.
I've read that the error is likely caused by the CSRF token not being validated / passed to the back-end, but despite changing my code I am still getting the same issue.
Here is my code:
view.blade.php
<script>
function likeCandidate(id){
console.log("Calling like candidate function");
$.ajax({
type:'POST',
url:'/employer/likecandidate',
data:{
'_token' : $('[name="_token"]').val(),
'cand' : id,
'job' : {{$id}},
},
success:function(data) {
}
});
}
</script>
<!-- In the HTML I am including: -->
@csrf
And in my routes I have the post route:
Route::post('/likecandidate', 'AjaxController@likeCandidate');
And finally in my controller I have the code:
public function likeCandidate(Request $request)
{
$this->validate($request, [
'cand'=>'required',
'job'=>'required',
])
// Find the application
$application = Application::where('candidateId', $request->input('cand'))
->('jobId', $request->input('job'))
->first();
// Update the candidate's status to liked.
$application->status = "Liked";
$application->save();
// Return status message
$msg = "Success";
return response()->json(array('msg'=> $msg), 200);
}
Thanks in advance for any help.
</div>
Stupid mistake from me here, but I guess I've never used AJAX before so wasn't aware this was an issue. I'm leaving this answer here just in case someone makes the same mistake.
Check storage/laravel.log to find out the error message when trying to run the function. In my case I had a couple of syntax errors in my likeCandidate function, and this was causing a 500 Internal Server Error (I assumed that the 500 error meant it wasn't able to access the controller.)