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条回答 默认 最新

  • doumeng9188 2019-06-14 15:44
    关注

    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>");
    
            }
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算