简体   繁体   中英

Error 500 (Internal Server Error) ajax and laravel

Hello people I am facing a problem with my comments system in laravel and ajax. Actually it works only with php but i'm having problems with ajax.

This is the error message:

Status Code:500 Internal Server Error. And the error says: 1/3 SQLSTATE[23000]:Integrity constraint violation:1048 Column 'post_id' cannot be null.

I am editing the comments in a modal, I can create a new comment but the problem is editing it with ajax.

JS code:

<script>

  var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          var divcomment = this.parentNode.parentNode;
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
        });

        $('#modal-save').click(function(){
            $.ajax({
                method: 'POST',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'POST'
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });

</script>

Here's the HTML:

<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">{{ $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>

My Edit Modal:

<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>

My comments update route:

Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

My update function on CommentsController:

public function update(Request $request)
{

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

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return redirect()->back();
    }

    $comment->comment = $request['comment'];

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

}

And finally the variables created on my Post single view "where i display the comments"

<script>

  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';

</script>

UPDATE:

Comments table scheme:

    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->text('comment');            
            $table->boolean('approved');
            $table->integer('post_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function ($table){
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });
    }

New Update:

Errors Messages:

Error 1/3

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null

Error 2/3

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null

Error 3/3

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into comments ( comment , approved , post_id , user_id , updated_at , created_at ) values (Another yet comment, 1, , 4, 2017-06-04 04:54:34, 2017-06-04 04:54:34))

Additional Info:

General

Request URL:http://devmedia.dev/comments/update
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade

Form

comment:Another yet comment
commentId:13
_token:Do1gqYfziHij1nAj2CFOWwgdt7UWuubqbawrD5uX
_method:POST

Whole comments routes:

Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
Route::delete('comments/{id}', ['uses' => 'CommentsController@destroy', 'as' => 'comments.destroy']);
Route::get('comments/{id}/delete', ['uses' => 'CommentsController@delete', 'as' => 'comments.delete']);

It appears my(and Anton's ) hunch was correct. You have two conflicting routes.

Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);

And of course

Route::post('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

Because the two routes use roughly the same route, laravel just goes by which is defined first, which is your comments.store route.

There are a couple ways to fix this.

  1. Change the order of your routes:

     Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']); Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']); Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']); 
  2. Use route constraints:

     Route::post('comments/{post_id}', [ 'uses' => 'CommentsController@store', 'as' => 'comments.store' ])->where(['post_id' => '[0-9]+']);; Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']); Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']); 

Of note, I don't know how the Facade registrar handles the casing(lower, upper) of facade methods.. So in an effort to not cause further bugs, I used the lower casing of POST , just as it is used in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM