本文介绍了使用ajax从数据库中获取关于帖子的评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ajax从数据库中获取每个帖子的所有comments,但是我遇到了一些问题.

这是问题.

我已经从数据库中获取了所有posts的home路线,而在那些帖子中却没有获取comments.

现在,我想使用Ajax为每个帖子获取comments,例如当某人对帖子发表评论时,应将其添加到数据库中,然后即时从数据库中获取.

评论已成功通过 Ajax 添加,但是我无法使用Ajax从数据库中获取它们.

这是我的代码:

控制器

Route::get('/home', 'HomeController@index')->name('home');
@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
中的

索引方法

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

我已经遍历了数据库中的所有帖子,因此我还在该循环内找到了一个表单,可以对该帖子发表评论.

** Form留下评论**

@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

当我单击注释按钮时,将运行以下代码以将注释插入comments .

Ajax请求

$(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>")

        }
    });
});


});

注释已成功添加到图像中提到的表中,并且我已经按照上述形式将其取回,但是当我刷新页面时会被获取,当有人在页面上留下评论时,我想获取它们.飞,因为它是通过ajax插入的,但是在刷新页面后才获取.

已更新

/comment代码在这里

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';
        }

}

带有虚拟"数据的注释表看起来像这样我正在尝试从最近2天开始解决此问题,请帮忙.谢谢

我为此研究的链接是

解决方案

表单代码更新.

@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

将数据存储在json响应中.

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

在ajax中需要显示我们已成功添加数据的消息

$.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>");

        }
    });

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 thisI'm trying to solve this problem from last 2 days, please help.Thanks

A link which I studied for this is this

解决方案

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>");

        }
    });

这篇关于使用ajax从数据库中获取关于帖子的评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:37