Juan Rincón
Juan Rincón

Reputation: 327

How to load specific div or id ajax and laravel

i have a comment system on my app in laravel and i can edit my comments with ajax but once edited it doesn't load automatically the edited comment. To see the edited comment i need to reload the page manually. I will put some of the code here.

This is the JS:

        var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          /* Accedemos al Div Que contiene el Panel*/
          var divcomment = this.parentNode.parentNode;
          /* Buscamos el Contenido con Id display-text  */
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
           /* Asignas a tu modal */
        });

        $('#modal-save').on('click', function(){
            $.ajax({
                method: 'PUT',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'PUT',
                    dataType: 'json',
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });

This is the Html:

 <article class="row">
                            <div class="col-md-3 col-sm-3 hidden-xs">
                              <figure class="thumbnail">
                                <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
                                <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                              </figure>
                            </div>
                            <div class="col-md-8 col-sm-8">
                              <div class="panel panel-default arrow left">
                                <div class="panel-body">
                                  <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                                  </header>
                                  <div id="comment-post" data-commentid="{{ $comment->id }}">
                                      <p id="display-comment">{{ $comment->comment }}</p>
                                  </div>
                                </div>

                                <div class="panel-footer list-inline comment-footer">
                                  @if(Auth::guest())

                                  No puedes responder ningún comentario si no has ingresado.

                                  @else

                                  @if(Auth::user() == $comment->user)
                                    <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
                                  @endif

                                  @if(Auth::user() != $comment->user)
                                    <a href="#">Responder</a>        
                                  @endif

                                  @endif
                                </div>

                              </div>
                            </div>
                          </article>

2 variables created on the view

  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';

and finally the modal where i edit the comment:

<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>

Everything's working but the only thing i need is to load the edited comment back without refresh the whole page, btw i used $('#display-comment').load(document.URL + ' #display-comment'); and with this line i succesfully load the edited comment but, it load all the comments on the edited one, so i have to refresh the whole page to show just the edited.

Upvotes: 3

Views: 2126

Answers (1)

Daedalus
Daedalus

Reputation: 7722

Assuming that the data sent to the php side of things is the same data that you then want to update to, the following should work:

$('#modal-save').on('click', function(){
    var comment = $('#comment').val();
    // shove the edited comment into a variable local to the modal handler
    $.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
            comment: comment, // reference said variable for ajax data
            commentId: commentId,
            _token: token,
            _method: 'PUT'
         },
         dataType: 'json'
    })
    .done(function (msg){
        //$(divcomment).text(msg['new_comment']);
        // I commented out the above line as it clears the
        // divcomment div's text entirely.
        // Comment out the below 'if check' if it is not needed.
        if (msg.success === true) {
            $(divcomment).find('#display-comment').text(comment);
            // And overwrite the #display-comment div with the new
            // data if the user was successful in editing the comment
        }
        $('#edit-comment').modal('hide');
    });
});

In a previous question of yours, you had a controller method on the php side of things that handled the ajax. Instead of redirecting(since it is ajax, there is no redirect), you should instead return json to indicate whether the action was successful or not. Here is an example of that:

public function update(Request $request)
{

    //...

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return response()->json(['success' => false], 200);
    }

    //...

    return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}

I referenced the above json in my answer on the javascript side of things; if you are not going to use the json response, then simply comment out the line(as I also noted in the code).

Update: I missed something in your earlier block of code; you declare divcomment outside of the edit link's handler, but then you re-declare it inside of that handler again. I missed this in my earlier answer, so simply deleting the var from it, so it uses the outside declaration, fixes your code:

var commentId = 0;
var divcomment = null; //this is already declared, no reason to declare it
// again

$('.edit-comment').click(function(event){
    event.preventDefault();
    /* Accedemos al Div Que contiene el Panel*/
    divcomment = this.parentNode.parentNode;
 // ^ remove the var, making this use the global variable you already
 // made above
    /* Buscamos el Contenido con Id display-text  */
    commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
    var commentBody = $(divcomment).find('#display-comment').text();
    $('#comment').val(commentBody);
    $('#edit-comment').modal();
    /* Asignas a tu modal */
});

Upvotes: 1

Related Questions