简体   繁体   中英

Laravel 5.8 post comment with ajax request without reloading DOM

I'm trying to post comments in my application without having to reload my page. I've got it working for deleting comments, but it isn't working for posting new ones. Can somebody please help??

Script for ajax request


// Add comments AJAX
$(".commentButton").click(function(){
    var id = $(this).data("id");
    var comment = $("input[name=comment]").val();
    var token = $(this).data("token");

    $.ajax({
       url: "/comments/"+id,
       type: 'POST',
       dataType: 'JSON',
       data: {
           "id": id,
           "comment": comment,
           "_method": 'POST',
           "_token": token,
       },

       success: function(){
        $("#comment_"+id).append(comment);
           console.log('it works!');
       } 
    });
    console.log("It failed");
});

CommentController


  public function store(Request $request, $recipe_id)
    {
        $this->validate($request, array(
            'comment' => 'required|min:5|max:2000'
        ));

        $recipe = Recipe::find($recipe_id);

        $comment = new Comment();
        $comment->name = auth()->user()->name;
        $comment->email = auth()->user()->email;
        $comment->comment = $request->comment;
        $comment->recipe()->associate($recipe); //I have relationship between 
        $comment->save();

        return $comment; 

Blade view where comments render


<div class="col-12 currentComments">
                            <hr>
                        @foreach($recipe->comments as $comment)
                            <div id="comment_{{ $comment->id }}">
                                @if($comment->name == Auth()->user()->name)
                                    <p><a href="/user/{{$comment->name}}">{{$comment->name}}</a></p>
                                    <p class="comment">{{$comment->comment}}</p>
                                    <button class="deleteComment" data-id="{{ $comment->id }}" data-token="{{ csrf_token() }}" >Delete Comment</button>
                                @else
                                @endif
                            </div>
                        @endforeach
                    </div>
                </div>

Where is this going worng? I know I'm missing something but I can't figure out what needs to be done. Fairly new to this. Forgive my ignorance.

I guess you should get comments using ajax to view. You can try something like below. I hope it will help you to reload comments after saving new comment without page refresh. In your blade file -

<div class="col-12 currentComments">
  <hr>
  <div id="allComments" class="allComments">
       <!--here your comments will render via ajax call-->
  </div>
  <input type="hidden" id="authuser" value="{{ Auth()->user()->name }}">      
</div>

In your script you can try something like -

<script>
    $(document).ready(function () {
        comment_load();
        function comment_loadad()
        {
          $.ajax({
              url: '/get-comment-list',
              type: 'GET',
              success: function (response) {
                  var authuser = $("#authuser").val();
                  $.each(response, function (i, data) {
                    $('.allComments').append(
                          '<div id="comment_"'+ data.id + '>' +
                           (data.name == authuser ? 
                               '<p><a href="/user/'+data.name+'">' +data.name +'</a></p>' +
                               '<p class="comment">'+data.comment+'</p>' +
                               '<button class="deleteComment" data-id="'+data.id+'">Delete Comment</button>'
                                : '') 
                          +'</div>');
                    });

                },
                error: function (data) {
                    //console.log(data);
                }
            });
        }
    }

And your // Add comments AJAX success method, please do append again -

success: function(data){                        
           var authuser = $("#authuser").val();
           $('.allComments').append(
                 '<div id="comment_"'+ data.id + '>' +
                   (data.name == authuser ? 
                   '<p><a href="/user/'+data.name+'">' +data.name +'</a></p>' +
                   '<p class="comment">'+data.comment+'</p>' +
                   '<button class="deleteComment" data-id="'+data.id+'">Delete Comment</button>'
                                : '') 
                 +'</div>');
           )
          $("input[name=comment]").val("");

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM