douquan2023
2019-06-14 13:47
浏览 87
已采纳

使用ajax从数据库获取对帖子的评论

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题