Mitch M
Mitch M

Reputation: 157

laravel - jquery/ajax Data empty

I'm trying to make my comment submit form work without refresh, and append the data into a div to show the comment. Currently the submit form works, it's inserted into the database so the data is passed to the controller, but it's not shown on console.log and the append.

JS

$("#newsCommentForm").submit(function(e){

  e.preventDefault();
    $.ajax({
      method: 'POST',
      url: '/store',
      data: $(this).serialize(),
      success:function(data){
          console.log( $( this ).serialize() );
        $('#test').append(data); 
      },
      error: function( e ) {
          console.log(e);
      }
  });
});

Controller

protected function storeNewsComment(Request $request)
{
     Comment::create([
         'user_id'  => Auth::user()->id,
         'blog_id'  => $request->input('blog_id'),
         'body'  => $request->input('body'),
     ]);
}

I made a test div in the view

<div id="test">

</div>

Upvotes: 0

Views: 231

Answers (2)

31piy
31piy

Reputation: 23859

this has a different meaning in the success callback function, which refers to the function's context. You need to save the reference to this before entering that function:

$("#newsCommentForm").submit(function(e){
  var self = this;
  // ... code truncated for brevity

  success: function() {
    console.log( $( self ).serialize() );
  }
 });

Upvotes: 0

Hedegare
Hedegare

Reputation: 2047

You just need to save the new comment to a variable and return it.

protected function storeNewsComment(Request $request)
{
    $comment = Comment::create([
        'user_id'  => Auth::user()->id,
        'blog_id'  => $request->input('blog_id'),
        'body'  => $request->input('body'),
    ]);

    return response($comment);
}

Upvotes: 1

Related Questions