0

I'm trying to fetch all the comments on each post from database using ajax, but I'm having some problem.

Here is the problem.

I've home route where I've fetched all the posts from database and I didn't fetched comments on those posts.

Now I want to fetch comments for each post using Ajax, such like when someone leave a comment on a post it should be added to the database and then fetch from database on the fly.

The comment is added via Ajax successfully , but I'm not able to fetch them from database using Ajax.

Here is my Code:

Controller

Route::get('/home', 'HomeController@index')->name('home');

index method inside HomeController

   public function index()
{

    $post  = Post::all();

    // I've used this approach to get comments
    //$posts = Post::with('comments')->get();


    return view('home')->with( array('posts'=>$posts ) );
}

I've loop through all the posts from the database , and so I've also a form there inside that loop to leave comment for that post.

** Form For leaving a Comment**

@foreach($posts as $post)
   <p>$post->description</p>

   <div class="show_comments_{{ $post->id }}"></div> 



  <form action="{{ url('comment',$post->p_id)  }}" method="POST"  > 
   @csrf
<textarea 
   name="body"
   placeholder="Write A Suggestion" 
   data-autosize-input='{ "space": 100 }' 
   rows="50" cols="100"
   name="comment"  
   class="form-control comment body">

 </textarea> 
 <input type="hidden" value="{{csrf_token()}}">


    <!-- user Id of the logged In one -->

  <input type="text" class="user_id" value="{{Auth::user()->id}}" name="user_id">

        <!-- post id  -->

  <input type="text" class="post_id" name="post_id" value="{{$post->p_id}}">



   <button type="button" class="btn btn-sm btn-danger formcomment" value = 'Comment' style="margin:10px;">Comment</button> 
</form>


@endforeach

When I click on Comment button the following code runs to insert the comment into the comments table.

Ajax Request

$(document).ready(function(){

     $('.formcomment').on('click', function(e) {
    e.preventDefault();

    var form = $(this).closest('form');
    // these are id's

    var body = form.find('.body').val();
    var post_id = parseInt(form.find('.post_id').val());
    var user_id = parseInt(form.find('.user_id').val());

    // alert(body);
    // alert('this is post'+post_id);
    // alert('This is user id'+user_id);


    $.ajax({
        type: "POST",
        url: '/comment/'+post_id,
        data: {body:body, post_id:post_id, user_id:user_id,  _token: '{{csrf_token()}}'},
        success: function(data) {


            $(".show_comments_"+post_id).append("<div style = 'color:red;'>"+data.msg+"</div>");
          $(".name_"+user_id).append("<div>"+data.user_id+"</div>")

        }
    });
});


});

The comments are added successfully to the table mentioned in the image, and I've fetched them back in the form mentioned above, but that is fetched when I refresh the page, I want to fetch them when someone leave comment on the fly, since it is inserting through ajax, but fetching after refreshing the page.

Updated

/comment code is here

public function storeComments(Request $request,Comment $body,$post_id){


 if($request->ajax()){
    $comment = new Comment;
    $comment->user_id =  Auth::user()->id;
    $comment->post_id = $post_id;
    $comment->body = Input::get('body');

    $comment->save();
    $response = array(
                'status' => 'success',
                'msg' => 'Setting created successfully',
            );
            return Response::json($response);
            return 'yes';
        }else{
            return 'no';
        }

}

comments table with 'dummy' data looks like this I'm trying to solve this problem from last 2 days, please help. Thanks

A link which I studied for this is this

contributor
  • 143
  • 3
  • 12

1 Answers1

0

Form code update.

@foreach($posts as $post)
   <p>$post->description</p>

    <div class="show_comments_{{ $post->p_id}}"></div>

  // I found this code on laracast, at end there is link.
   @if (count($post->comments))
       @foreach($post->commnents as $comment)
         <small>$comment->body</small>
       @endforeach
    @else 
        No comments Found
  @endif 

store the data in json response.

if($request->ajax()){
    $comment = new Comment;
    $comment->user_id =  Auth::user()->id;
    $comment->post_id = $post_id;
    $comment->body = Input::get('body');

    $comment->save();
   //add the comment in response 
    return response()->json(['msg'=>$comment->body]);
}

in ajax need to display the message that we have successfully added the data

$.ajax({
        type: "POST",
        url: '/comment/'+post_id,
        data: {body:body, post_id:post_id, user_id:user_id,  _token: '{{csrf_token()}}'},
        success: function(data) {
            //get the msg from success response. 
               $(".show_comments_"+post_id).append("<div style = 'color:red;'>"+data.msg+"</div>");

        }
    });
Shivendra Singh
  • 2,986
  • 1
  • 11
  • 11
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/194974/discussion-on-answer-by-shivendra-singh-get-comments-on-a-post-from-database-usi). – Samuel Liew Jun 15 '19 at 04:57