mardi 19 janvier 2016

405 Method not allowed - Laravel Ajax

I'm developing a laravel 5.1 application. It is working perfectly fine on my localhost but when I deploy it on the shared hosting, it is giving 405 (method not allowed) on liking a post via ajax request.

Following is the controller method:

public function likePost($id){
    if(\Auth::check()){
        $post = Post::findOrFail($id);
        $userId = \Auth::id();
        if($post->liked($userId)){
            $post->unlike($userId);
        }else{
            $post->like($userId);
        }
    }
}

The javascript including Ajax request is:

<script type="text/javascript">
            $(document).on("click", 'button.like-btn', function(event){
                // $('button.like-btn').click(function(){

                    var post_id = $(this).data('id');
                    var url = "/posts/"+ post_id +"/like";
                    url = url.replace(/\/?(\?|#|$)/, '/$1');
                    var token = $('meta[name="_token"]').attr('content');

                    $.ajax
                    ({  
                        type: 'POST',
                        url: url,
                        data: {"_token": token},
                        success: function()
                        {   
                            if ($('button.like-btn[data-id="'+post_id+'"]').hasClass('green')){
                                $('button.like-btn[data-id="'+post_id+'"]').removeClass('green');
                                $('#postLikeCount[data-post-id="' + post_id + '"').html(parseInt($('#postLikeCount[data-post-id="' + post_id + '"').html(), 10)-1);
                            }else{
                                $('button.like-btn[data-id="'+post_id+'"]').addClass('green');
                                $('#postLikeCount[data-post-id="' + post_id + '"').html(parseInt($('#postLikeCount[data-post-id="' + post_id + '"').html(), 10)+1);
                            }
                        },
                        error: function(xhr, textStatus, errorThrown){
                           alert('Cannot like the post yet. Please try again later.');
                        }
                    });
                });
            </script>

And my registered route is:

Route::post('posts/{id}/like', ['uses' => 'PostsController@likePost']);

Why is it generating the following error with GET status? error

How can I resolve this? Any help will be appriciated



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire