not logged in
Mar 13, 2021
30
Level 1
Getting response()->json() as undefined in consolelog
I was working on overtrue/laravel-follow package and was using ajax call to follow a user and unfollow. scripts file includes:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.btn-follow').click(function() {
let user_id = $(this).data('id');
let object = $(this);
$.ajax({
type: 'POST',
url: '/follow',
data: { user_id: user_id },
dataType: 'json',
success: function(data) {
console.log(data.success);
},
});
});
});
User Controller Follow method:
public function follow(Request $request)
{
$authUser = Auth::user();
$user = User::findOrFail($request->user_id);
if ($authUser !== null && $authUser instanceof User) {
$response = $authUser->toggleFollow($user);
return response()->json(['success' => $response]);
}
}
Routes:
Route::post('/follow', 'UserController@follow')->name('user.follow');
I'm getting undefined object in the console and no object with attached and detached. What is the problem
PS: It is surprising that method is still working and follow unfollow is working behind the scene
Level 122
query the follower status after toggle and return that.
$user = User::find($request->user_id));
Auth::user()->toggleFollow($user);
return response()->json(['following' => Auth::user()->isFollowing($user)]);
will return 200 status and true if following and false if not
2 likes
Please or to participate in this conversation.