Juan Rincón
Juan Rincón

Reputation: 327

How to Send a Form post Using Ajax in Laravel 5.4

I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into comments (comment, approved, user_id, post_id, updated_at, created_at) values (sdfsdfsdff, 1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

<?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 code in the view

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');
      }
   });
});

Form

<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>

Comments 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>

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error) "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

Upvotes: 0

Views: 344

Answers (3)

Maaz
Maaz

Reputation: 67

Your form id is "add-comment" but in your ajax you are serializing your form through "comment-new". And you did not define name="id" field in your form which you are getting in your controller.

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

Upvotes: 1

plmrlnsnts
plmrlnsnts

Reputation: 1684

I assume that your route looks like this

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

You can access the route parameter {id} in your request by

$request->route('id');

But since you're inside a controller, you can just access the parameter in your store function

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

Upvotes: 0

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Yes you are right. It is not relationship problem. But I have the hack I guess, As you have $post_id here $post = Post::find($post_id); then why do you use $request->id here in this line? $comment->post_id = $request->id;

I doubt that $request->id is not having post id.

Try using this way:

$comment->post_id   = $post_id;

Upvotes: 0

Related Questions