doufang6268 2017-03-19 12:02
浏览 95
已采纳

Laravel 5.2上的Ajax请求失败

I'm working on a blog commenting feature on a website but I am having some challenges getting the commenting ajax request feature to work.

Here's my code below

Form

    {!! Form::open(['id' => 'comment_form']) !!}
     <div>
     {!! Form::hidden('article_id', $article->id) !!}
    </div>
    <div>
     {!! Form::hidden('user_id', 1) !!}
     {!! Form::hidden('username','name') !!}
     {!! Form::hidden('email','fname.lname@mail.com') !!}
     {!! Form::hidden('password','**__**') !!}
     {!! Form::hidden('service_id', 1) !!}
   </div>
   <div class="form-group">
     {!! Form::textarea('comment', null, ['class' => 'form-control', 'placeholder' => "Keep your comments to less than 250 chars"]) !!}
   </div>
   <div class="form-group">
     {!! Form::submit('Post!',['class' => 'btn btn-primary form-control', 'id' => 'comment' ]) !!}
   </div>
    {!! Form::close() !!}

Then below is my Ajax request using jQuery

$('#comment_form').on('submit', function(e) {

    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    });

    e.preventDefault(e);

    $.ajax({
        type: "POST",
        url: '/articles/comment',
        data: $(this).serialize(),
        dataType:'json',
        delay: 2000,
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log("Failure");
        }
    });
});

And the Receiving Controller snippet is shown below

public function enterComment(Request $request)
    {


        // First check that the commenter is logged in with the session controller
        // If not force the person to be logged in

        $this->validate($request, ['comment' => 'required','user_id' => 'required']);

        try{
            // I am supposed to use the user_id record which is in the session.
            // However since I don't have my session variable created and model working
            // I will use this
            $user = User::where('user_id',$request['user_id'])->firstOrFail();
        }
        catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            // Ask user to to register his details.
            // For action tomorrow
            $user = User::create(['username'=> $request['username'],'email' => $request['email'],'password' => $request['password'],'service_id' => $request['service_id']]);
        }
        // Register comment
        $comment = new Comment;
        $comment->comment = $request['comment'];
        $comment->article_id = $request['article_id'];
        $comment->user_id = $request['user_id'];
        $comment->published_at = Carbon::now();
        $comment->save();
        dd($comment,$user);

        return response()->json(['comment' => $comment->comment], 200);
    }

That's what I am troubleshooting now and unfortunately I have not been able to figure out what I am doing wrong. Please can anyone help me out with this.

  • 写回答

1条回答 默认 最新

  • dtr32787 2017-03-20 00:35
    关注

    There were a couple of issues. One was the way I was accessing the form data. I changed my request collection approach to $request->input(), which generated an array of all the items from the form. Then in the jQuery ajax function I changed the data collection method to

    data:$(this).serializeArray().

    This made the data easy to parse in the controller. Finally I changed the return response()->json(['comment' => $comment->comment], 200); to a simple return json_encode($request['comment']);

    Thanks everyone for your help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置