3

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.

Daedalus
  • 7,586
  • 5
  • 36
  • 61
Juan Rincón
  • 307
  • 5
  • 15
  • You have the comment from the modal; is there a reason you cannot use the data contained within the modal? It is the same data, is it not? – Daedalus Jun 07 '17 at 02:12
  • @Daedalus well this works like this, the modal contains the comment id, then i edit the comment, once edited the comment should be pass through the modal to the id="display-comment". So in theory the data in the modal should replace the old id="display-comment" data.. or at least that's what i'm looking for. – Juan Rincón Jun 07 '17 at 06:20
  • So, why can't you just do that? `$(divcomment).find('#display-comment').text(comment)`, as the last line in your ajax's done function. – Daedalus Jun 07 '17 at 06:57
  • Also, please stop using the snippet feature for non-snippet code. If you just have code to indent, use the curly braces button: `{}`, not the snippet button, which is used to demonstrate runnable javascript, css, or html code. See [here](https://meta.stackoverflow.com/questions/269753/feedback-requested-runnable-code-snippets-in-questions-and-answers) for more information. – Daedalus Jun 07 '17 at 23:09
  • @Daedalus sorry about the snippet feature, i'm new. About the code, the same, i need to reload manually the page to see the edited comment – Juan Rincón Jun 08 '17 at 00:29
  • You have the edited comment's content. Why can you not just use that? – Daedalus Jun 08 '17 at 03:29
  • @Daedalus i'm using it.. the only thing i need is just to load the edited comment – Juan Rincón Jun 08 '17 at 19:27
  • The line I gave you does that. – Daedalus Jun 08 '17 at 19:58
  • @Daedalus unfortunately `code $(divcomment).find('#display-comment').text(comment)` and the same :/ – Juan Rincón Jun 08 '17 at 20:39
  • How many elements do you have with that id? – Daedalus Jun 08 '17 at 20:56
  • with #display-comment? – Juan Rincón Jun 08 '17 at 21:03
  • Yes, with #display-comment. – Daedalus Jun 08 '17 at 21:23
  • @Daedalus #display-comment is only on this line `code

    {{ $comment->comment }}

    `
    – Juan Rincón Jun 08 '17 at 22:02
  • Then I am not understanding how 'the entire page' is reloaded by changing the content of one comment. If that isn't what you meant, please clarify what you meant when you said "and the same :/" – Daedalus Jun 08 '17 at 22:17
  • @Daedalus the entire page isn't reloading, when i press on edit comment the modal close and to see the edited comment i need to reload the entire page manually. When i said "and the same" i mean, once i added the `$(divcomment).find('#display-comment').text(comment)` i need to reload the whole page manually to see the edited comment "the new lines added to comment". The only way to see the edited comment is reloading the whole page because it don't load automatically the edited comment. – Juan Rincón Jun 08 '17 at 22:27
  • I see now I made a mistake; I was operating off of a false understanding of the code present. The following line should solve the problem: `$(divcomment).find('#display-comment').text($('#comment').val());`. If it does not; create a variable local to the click handler of the modal: `var comment = $('#comment').val();`, then reference said variable in the done handler. – Daedalus Jun 08 '17 at 22:31
  • This line is giving me a problem `$(divcomment).find('#display-comment').text($('#comment').va‌​l());` the modal is not opening @Daedalus – Juan Rincón Jun 08 '17 at 23:05
  • I didn't really want to, but I posted an answer, since the expanded code couldn't really fit in a comment. – Daedalus Jun 08 '17 at 23:23

1 Answers1

1

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 */
});
Daedalus
  • 7,586
  • 5
  • 36
  • 61
  • doesn't load automatically the comment... i don't know what else to do @Daedalus – Juan Rincón Jun 09 '17 at 01:14
  • @JuanRincón Without any errors, or a better description of the problem, I don't know either. – Daedalus Jun 09 '17 at 01:16
  • no errors. this is what the chrome console gaves me: `{new_comment: "Primer Comentario editado...", success: true} new_comment : "Primer Comentario editado..." success : true` and form data: `comment:Primer Comentario editado... commentId:1 _token:6llgVyfmAstqHEuVpnrXpS4hg0u8yRHfnaoD9ff5 _method:PUT dataType:json` – Juan Rincón Jun 09 '17 at 01:20
  • @JuanRincón Please show a screen shot of the console; otherwise it is not clear how you are getting two objects in the json. – Daedalus Jun 09 '17 at 01:26
  • [link]() [link2]() [link3]() @Daedalus – Juan Rincón Jun 09 '17 at 01:38
  • @JuanRincón Do `console.log(msg)` in your `done` handler. If the object that is logged has a success property which evaluates to true, then I am not sure how it is failing. Also, I fixed your `dataType` parameter; it should not be in the data object, but in the settings object. See the answer's code for details. – Daedalus Jun 09 '17 at 01:42
  • @JuanRincón I already looked at the pictures; everything seems fine. Check the actual console for the log. – Daedalus Jun 09 '17 at 02:16
  • i've checked the console and i agree with you, looks good, i don't know whats happening @Daedalus – Juan Rincón Jun 09 '17 at 02:20
  • @JuanRincón Please post an update to your question with your current code. – Daedalus Jun 09 '17 at 02:26
  • yessss!!! you did it. Thank you sooo much dude, i didn't realised that the var = divcomment was null and i was making a new var with the same name.. really appreciate your hours, time and help! – Juan Rincón Jun 09 '17 at 04:08
  • sorry for this new question, to create the comments with ajax is the same way than edit? – Juan Rincón Jun 09 '17 at 04:36
  • @JuanRincón Roughly; you might have to make some changes, such as using classes rather than Ids, if you plan on having multiple comments on the same page. – Daedalus Jun 09 '17 at 05:03
  • actually i have the comments crud, so to create the comments via ajax i need to add a class to the paragraph where i have the #display-comment? i mean, class="put-comment" for example – Juan Rincón Jun 09 '17 at 05:18
  • @JuanRincón Well, you need to have an ajax method in place to target that specific route. – Daedalus Jun 09 '17 at 06:20
  • hmm i see, i will check – Juan Rincón Jun 09 '17 at 15:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/146337/discussion-between-juan-rincon-and-daedalus). – Juan Rincón Jun 10 '17 at 21:34