如何在Laravel 5.4中使用Ajax发送表单帖子

时间:2017-12-04 11:27:31

标签: php ajax laravel laravel-5 laravel-5.4

我尝试使用POST方法发送表单,但我收到了查询异常错误。

  

SQLSTATE [23000]:完整性约束违规:1048列' post_id'   不能为空(SQL:插入commentscommentapproved,   user_idpost_idupdated_atcreated_at)值(sdfsdfsdff,   1,1,2017-12-04 07:18:13,2017-12-04 07:18:13))

' sdfsdfsdff'是我试图发送给"评论系统的评论",1是用户ID,空格是post id应该是的位置。

控制器

<?php

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

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);

视图中的Ajax代码

var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '<p class="store-comment">' + data.comentario + '</p>'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});

表格

<div class="row">
    <div class="col-xs-8 col-md-offset-2 form-create">
        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}
    </div>
</div>

评论HTML

<div class="row">
        @foreach ($post->comments as $comment)
            <section class="comment-list">
                <article class="row">
                    <div class="col-md-3 col-sm-3 hidden-xs">
                        <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}"/>
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                        </figure>
                    </div>
                    <div class="col-md-8 col-sm-8">
                        <div class="panel panel-default arrow left">
                            <div class="panel-body">
                                <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}
                                    </div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i
                                                class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}
                                    </time>
                                </header>
                                <div id="comment-post" data-commentid="{{ $comment->id }}">
                                    <p id="display-comment"
                                       class="store-comment" {{ $comment->id }} {{ $post->id }}>{{ $comment->comment }}</p>
                                </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a>
                                        <a href="#" data-toggle="modal" data-target="delete-comment"
                                           class="delete-comment">Eliminar</a>
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        <a href="#">Responder</a>
                                    @endif
                                @endif
                            </div>
                        </div>
                    </div>
                </article>
            </section>
        @endforeach
</div>

主要错误:

  

POST http://localhost:8000/comments/store 500(内部服务器错误)   &#34;来自Google Chrome控制台&#34;

在我的数据库评论表中,当我没有使用Ajax时,我确实有一个完美的外键,所以我不认为这是一个关系问题。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您的表单ID是“添加评论”,但在您的ajax中,您通过“comment-new”序列化您的表单。 并且您没有在表单中定义name =“id”字段,而是在控制器中。

$comment->post_id   = $request->id;

答案 1 :(得分:0)

是的,你是对的。 这不是关系问题。但我觉得我有黑客攻击, 由于你在这里有$ post_id $post = Post::find($post_id);,为什么你在这行使用$ request-&gt; id? $comment->post_id = $request->id;

我怀疑$ request-&gt; id没有帖子ID。

尝试使用这种方式:

$comment->post_id   = $post_id;

答案 2 :(得分:0)

我认为你的路线看起来像这样

Route::post('comments.store/{id}', ...);

您可以通过

访问请求中的路由参数{id}
$request->route('id');

但由于你在控制器内部,你可以只访问store函数中的参数

public function store($id) {
    echo $id;
}