简体   繁体   中英

laravel AJAX post

I am trying to learn using AJAX with laravel, my knowledge of AJAX is practically zero. The last few days I tried to solve this. But I can't get it to work...

Basically when a user clicks the like button of a post, I want to submit that request to my LikeController. The LikeController works so that can't be the issue, it seems that no data is passed by AJAX to the Controller. Can someone point out what I am doing wrong?

My route:

Route::post('posts/like', [
    'as' => 'posts.like', 
    'uses' => 'LikeController@likePost'
]); 

My controller:

public function likePost(Request $request)
    {
        // Validation
        $this->handleLike('App\Post', $request['postId']);
        return response()->json(['msg' => 'success'], 200);
    }

    public function handleLike($type, $postId)
    {
        $existing_like = Like::withTrashed()->whereLikeableType($type)->whereLikeableId($postId)->whereUserId(Auth::id())->first();

        if (is_null($existing_like)) {
            Like::create([
                'user_id'       => Auth::id(),
                'likeable_id'   => $postId,
                'likeable_type' => $type,
            ]);
        } else {
            if (is_null($existing_like->deleted_at)) {
                $existing_like->delete();
            } else {
                $existing_like->restore();
            }
        }
    }

And the JS:

$('.like').on('click', function(event) {
    event.preventDefault();

    postId = event.target.dataset['postid'];

    console.log(postId)
    console.log(token) 

    $.ajax({
        method: 'POST',
        url: urlLike,  // Gets defined in the view
        data: {postId: postId, _token: token}
    }).done(function(msg) {
           console.log(msg); // never even reached this stage...
    });
});

What output do you get in the console? error 500?

For ajax to work, you need to send the csrf token with your request.

https://laravel.com/docs/master/routing#csrf-x-csrf-token

To properly debug ajax request i recommend you to use artisan tail, this helps you to watch error messages when working with ajax.

https://github.com/spatie/laravel-tail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM