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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题