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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧