喜欢/不喜欢jQuery AJAX返回500(内部服务器错误),但在我重新加载页面时工作

时间:2016-07-30 00:14:54

标签: javascript php jquery ajax laravel-5

我有一个Like Status按钮,可以使用AJAX将数据发送到控制器。

当我点击按钮时,按钮变为"喜欢"到"不喜欢"并且所有类和表单操作也都会被更改。

问题是,如果我喜欢这种状态,我会看到所反映的变化,但如果我决定不重新加载页面,我就会收到此错误

  

获取http://localhost/socialnet/public/likestatusCount/undefined 500(内部服务器错误)

如果我重新加载页面并点击不喜欢,我的投票将从数据库中删除,按钮会变回"喜欢"

如果我重新加载页面,它会起作用。

如果我删除了get()请求以检索喜欢的计数,则没有任何反应,而console.log()会返回一个空行,我也看不到任何返回的数据。

我打开了laravel.log,我看到了这个错误

  

local.ERROR:exception' ErrorException'与消息'试图获得非对象的属性'在C:\ xampp \ htdocs \ socialnet \ app \ Http \ Controllers \ FeedController.php:140

这是getlikesCounter()方法

中的这一行

return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);

我正在使用Laravel 5.2

视图中的表单

@if(\App\StatusLikes::where(['status_id' => $status->id, 'user_id' => Auth::user()->id])->first())
    {!! Form::open(['action' => 'FeedController@dislikeStatus', 'id' => 'dislike_form', 'class' => 'dislikeform']) !!}
    <button type="submit" class="btn btn-danger btn-xs dislike" data-user="{{ Auth::user()->id }}" data-status="{{ $status->id }}" id="dislike-status">
       <i class="fa fa-thumbs-down"></i> <span class="dislike-button-text">Dislike</span> <span class="dislike-button-counter">({{ $likes_count }})</span>
    </button>
   {!! Form::close() !!}
   @else
   {!! Form::open(['action' => 'FeedController@likeStatus', 'id' => 'like_form', 'class' => 'likeform']) !!}
     <button type="submit" class="btn btn-info btn-xs like" data-user="{{ Auth::user()->id }}" data-status="{{ $status->id }}" id="like-status">
       <i class="fa fa-thumbs-up"></i> <span class="like-button-text">Like</span> <span class="like-button-counter">({{ $likes_count }})</span>
      </button>
   {!! Form::close() !!}
@endif

控制器中的类似,不喜欢和喜欢的方法计数

public function likeStatus() {
    if (Input::has('like_status')) {
        $status = Input::get('like_status');
        $selectedStatus = Status::find($status);

        $selectedStatus->likes()->create([
            'user_id' => Auth::user()->id,
            'status_id' => $status
        ]);

        $response = [
            'status' => 'success',
            'msg' => 'You have liked this status',
        ];

        return Response::json($response);
        //return redirect(route('feed'));
    }
}

public function dislikeStatus() {

    if (Input::has('dislike_status')) {
        $status = Input::get('dislike_status');
        $selectedStatus = Status::find($status);

        $selectedStatus->likes()->where('user_id', Auth::user()->id)->delete([
            'status_id' => $status
        ]);

        $response = array(
            'status' => 'success',
            'msg' => 'You have disliked this status',
        );

        return Response::json($response);
        //return redirect(route('feed'));

    }
}

public function getlikesCounter($id) {
    $status = Status::find($id);
    return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
}

javascript表单likeformdislikeform

$('.likeform').submit(function(e) {
    e.preventDefault();

    var submitBtn = $(this).find('.like');
    var form = $(this).find('.likeform')
    var likeText = $(this).find('span.like-button-text');
    var likeCounter = $(this).find('span.like-button-counter');
    var status_id = submitBtn.data('status');
    var user_id = submitBtn.data('user');
    var token = $('input[name=_token]').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': token
        }
    });

    $.ajax({
        url: 'http://localhost/socialnet/public/likeStatus',
        method: 'POST',
        cache: false,
        data: { like_status: status_id, user_id: user_id, _token: token },
        success: function(data) {
            submitBtn.removeClass('btn-info').addClass('btn-danger');
            submitBtn.find($(".fa")).removeClass('fa-thumbs-up').addClass('fa-thumbs-down');
            submitBtn.closest("form").removeClass('likeform').addClass('dislikeform').attr('id', 'dislike_form').attr('action', 'http://localhost/socialnet/public/dislikeStatus');
            submitBtn.closest("form").find("input[name=like_status]").attr('name', 'dislike_status');
            submitBtn.removeClass('like').addClass('dislike');
            submitBtn.find($(".like-button-text")).removeClass('like-button-text').addClass('dislike-button-text');
            submitBtn.find($(".like-button-counter")).removeClass('like-button-counter').addClass('dislike-button-counter');
            likeText.text('Dislike');

            $.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
                likeCounter.text('(' + data.count + ')');
            });

            console.log(data);
        },
        error: function() {
            console.log('error');
        }
    });
});

$('.dislikeform').submit(function(e) {
    e.preventDefault();

    var submitBtn = $(this).find('.dislike');
    var form = $(this).find('.dislikeform')
    var likeText = $(this).find('span.dislike-button-text');
    var likeCounter = $(this).find('span.dislike-button-counter');
    var status_id = submitBtn.data('status');
    var user_id = submitBtn.data('user');
    var token = $('input[name=_token]').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': token
        }
    });

    $.ajax({
        url: 'http://localhost/socialnet/public/dislikeStatus',
        method: 'POST',
        cache: false,
        data: { dislike_status: status_id, user_id: user_id, _token: token },
        success: function(data) {
            submitBtn.removeClass('btn-danger').addClass('btn-info');
            submitBtn.find($(".fa")).removeClass('fa-thumbs-down').addClass('fa-thumbs-up');
            submitBtn.closest("form").removeClass('dislikeform').addClass('likeform').attr('id', 'like_form').attr('action', 'http://localhost/socialnet/public/likeStatus');
            submitBtn.closest("form").find("input[name=dislike_status]").attr('name', 'like_status');
            submitBtn.removeClass('dislike').addClass('like');
            submitBtn.find($(".dislike-button-text")).removeClass('dislike-button-text').addClass('like-button-text');
            submitBtn.find($(".dislike-button-counter")).removeClass('dislike-button-counter').addClass('like-button-counter');
            likeText.text('Like');

            $.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
                likeCounter.text('(' + data.count + ')');
            });

            console.log(data);
        },
        error: function() {
            console.log('error');
        }
    });
});

1 个答案:

答案 0 :(得分:0)

GET http://localhost/socialnet/public/likestatusCount/undefined 500 (Internal Server Error)

意思是:

status_idundefined

因为,你有:

        $.get("http://localhost/socialnet/public/likestatusCount/" + status_id//..

确实,你status_id来自:

 var status_id = submitBtn.data('status'); 

你有submitBtn来自:

 var submitBtn = $(this).find('.dislike');

但是,当有动作(比如/不喜欢)时,你会更改submitBtn的CSS类

因此,

  • .dislike在这里是错误的选择器,您需要一个与按钮匹配的选择器,无论是喜欢还是不喜欢

  • 将值分配给submitBtn&amp;在调用您的ajax之前更新status_id

        $.get("http://localhost/socialnet/public/likestatusCount/" + status_id//..