muhammad aditya
muhammad aditya

Reputation: 63

AJAX+Laravel: after I successfully do process in AJAX, other functions are not working

Sorry my english not good :)

I have problem with AJAX success in Laravel, after I successfully do process in AJAX, other functions are not working. Like the picture below, I like status or comment, function of collapse button and favorite button does not work.

In AJAX success I use

 $("#divwrap").load(" #divwrap");

div with an id of divwrap I use as a wrapper

Please help :)

Code

<div id="divwrap">
  @foreach($singgah as $d)    
  <div class="box box2">
    <div class="box-body box-body-custom">
      <div class="post">
        <div class="user-block">
          <img class="img-circle" src="{{ asset('storage/' . $d->user->avatar ) }}" alt="user image">
          <span class="username">
            <?php $email = Crypt::encrypt($d->user->email) ?>
            <a href="{{ action('ProfileController@show', $d->user->email) }}">{{$d->user->name }} </a>  
            <div class="btn-group pull-right custom-curret nav-right1">
              <button type="button" class="btn btn-primary-outline dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <span class="fa fa-ellipsis-h"></span>
              </button>
              <ul class="dropdown-menu">
                @if(Auth::user()->name ==$d->user->name )
                  <li><a onclick="editForm('{{$d->id }}')" class="pointer-jempol"> <i class="fa fa-pencil-square-o"></i> Edit Kiriman</a></li>
                  <li><a onclick="deleteData('{{$d->id }}')" class="pointer-jempol"> <i class="fa fa-times-circle"></i> Hapus Kiriman</a></li>
                  <li role="separator" class="divider"></li>
                @endif
                <li><a href="#" class="pointer-jempol"><i class="fa fa-exclamation-circle"></i> Laporkan Kiriman</a></li>
              </ul>
            </div>
          </span>
          <span class="description"><i class="fa fa-hashtag" title="Sebagai"></i>  {{$d->category}} - <i class="fa fa-clock-o"></i> {{$d->created_at->diffForHumans()}}</span>
        </div>        
        <p>
          {{ $d->content }}            
        </p>
        <div class="box box-default box-costum-collapse">
          <div class="box-header with-border" style="padding:0px;">
            <a class="label label-primary" title="Kota"><i class="fa fa-map-marker"></i> {{$d->lokasi }}</a>
            <a class="label label-primary" title="Kontak"><i class="fa fa-phone-square"></i> {{$d->contact }}</a>
              <table class="pull-right">
                <tr>
                    <td class="mailbox-star" data-value="{{$d->id}}"><i class="fa fa-star-o text-red"></i> <a id="coba">{{ $d->singgahlike->count() }}</a></td> 
                    <td class="btn-nopadding btn btn-box-tool" data-widget="collapse"> | <i class="fa fa-comment"></i> {{ $d->singgahcomment->count() }}</td>
                </tr>
              </table>
          </div>
          <div class="box-body" style="padding:0px;">
            <div class="box-komentar">
              @include('layouts.form.formComment')
              <div id="box-komentar">
              @foreach($d->singgahcomment as $c)
                <div class="komentar-post"> 
                  <div class="user-block">
                    <img class="img-circle" src="{{ asset('storage/' . $c->user->avatar ) }}" alt="user image">
                    <span class="username usernamekoment">
                      <a href="{{ action('ProfileController@show', $c->user->email) }}">{{$c->user->name }} </a>  
                      <div class="btn-group custom-curret nav-right-koment pull-right">
                        <button type="button" class="btn btn-primary-outline dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          <span class="fa fa-ellipsis-h"></span>
                        </button>
                        <ul class="dropdown-menu">
                          @if(Auth::user()->name ==$c->user->name )
                          <li><a onclick="deleteComment('{{$c->id }}')" class="pointer-jempol"><i class="fa fa-times-circle"></i> Hapus Komentar</a></a></li>
                          <li role="separator" class="divider"></li>
                          @endif
                          <li><a href="#" class="pointer-jempol"><i class="fa fa-exclamation-circle"></i> Laporkan komentar</a></li>
                        </ul>
                      </div>
                    </span>
                    <span class="description descriptionkoment"><i class="fa fa-clock-o"></i> {{$c->created_at->diffForHumans()}}</span>
                  </div>                 
                  <p>{{ $c->comment }}</p>
                </div>
              @endforeach
              </div>
            </div>
          </div>
        </div>
      </div>                            
    </div>
  </div>      
  @endforeach
</div>

and this is one ajax success process:

 $(function () {
  $(".mailbox-star").click(function (e) {
    e.preventDefault();
    var singgah_id = $(this).data('value');
      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
      });
      $.ajax({
      url: "{{ url('singgah/like') }}",
      type: "POST",
      data: {singgah_id:singgah_id},
        success: function (data) {
          $("#divwrap").load(" #divwrap");  
          $('div.flash-message').html(data);
        },
        error: function () {
          alert('Oops! error!');
        }
      });
    //detect type
    var $this = $(this).find("i");
    var fa = $this.hasClass("fa");
    if (fa) {
      $this.toggleClass("fa-star");
      $this.toggleClass("fa-star-o");
    }
  });
});

Below I show a button that works only once before the AJAX success button is working, but after the AJAX success button it becomes not working

below I show a button that works only once before the ajax success button is working, but after the AJAX success button it becomes not working

Upvotes: 0

Views: 96

Answers (1)

Salar Bahador
Salar Bahador

Reputation: 1494

It's because after jQuery changes and loads the elements of the DOM again, even if the id and class names are the same but the virtual id of the DOM elements are changed and javascript or jQuery assume this is different than previous ones.

In other words, jQuery attaches to elements on loading of DOM, so after done loading, it can't recognize the new elements. to do that you must get the elements from the document instead.

So your code will look like this:

$(document).on('click', ".mailbox-star", function (e) {
    e.preventDefault();
    var singgah_id = $(this).data('value');
      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
      });
      $.ajax({
      url: "{{ url('singgah/like') }}",
      type: "POST",
      data: {singgah_id:singgah_id},
        success: function (data) {
          $("#divwrap").load(" #divwrap");  
          $('div.flash-message').html(data);
        },
        error: function () {
          alert('Oops! error!');
        }
      });
    //detect type
    var $this = $(this).find("i");
    var fa = $this.hasClass("fa");
    if (fa) {
      $this.toggleClass("fa-star");
      $this.toggleClass("fa-star-o");
    }
  });

Notice this line:

$(document).on('click', ".mailbox-star", function (e) {

instead of this:

$(function () {
  $(".mailbox-star").click(function (e) {

So if you want to events work after reloading part of DOM you must address the selector from the document. Note that the selecting of element works a little bit slower than the first one.

Upvotes: 2

Related Questions