My code gives me 500 Internal Server error when trying to make AJAX POST request. I've done the CSRF Token part.
This is my JS code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#likeBtn').on('click', function(e){
e.preventDefault();
//Getting urlLink and activityId - works
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId},
success: function(data){
console.log(JSON.stringify(data));
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
This is my post Route :
Route::post('/mainView/postlike', 'ActivityController@postLike')->name('postLike')->middleware('auth');
This is my controller method :
public function postLike(){
if(Request::ajax()){
return Response::json(Request::all());
}
}
This is my mainView.blade.php. I didn't really want to use a form but I tried anyway.
<form id="likeForm" method="POST" action="#">
<input class="likeToken" type="hidden" name="_token" value="{{ csrf_token() }}">
<a id="likeBtn" data="{{ route('activity.like', ['activityId' => $activity->activity_id]) }}">
<img src="IMG/icons/like.png" alt="likes">
</a>{{ $activity->likes->count() }}
</form>
That being said, if I do this in my route, it outputs the message provided.
Route::post('/mainView/postlike', function(){
if(Request::ajax()){
echo "Hi";
}
})->name('postLike')->middleware('auth');
It shows "Hi" when the like button is pressed