0

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>
3
  • 1
    what output would you expect? is storeNewsComment() your action? if so, why is it protected? Also, it is not returning anything Commented Jul 21, 2018 at 10:31
  • Didn't realize the controller would need to return anything, I thought since data is defined in the Ajax and the console.log is called there, it's also stored there. What should I return then? I expect the output to be the userid/blogid/body Commented Jul 21, 2018 at 10:32
  • Thanks, you've put me on the right track and it works now. Commented Jul 21, 2018 at 10:42

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

$return_array = compact('comment'); return json_encode($return_array); seemed to work for me.
@MitchM Well, you can return the data the way it suits better your frontend.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.