Khairul
Khairul

Reputation: 425

jQuery - Function on Hide Modal Not Working After Ajax Success On First Run

I have make an Ajax Request and want to hide the modal after success. The problem that I am facing are, the function inside the hide method is not working on first call but if I do it again, it is working. Below are the codes:

HTML

<table class="table table-hover">
    <thead>
        <tr>
            <th scope="col">User Id</th>
            <th scope="col">Time In</th>
            <th scope="col">Status</th>
            <th scope="col">LAST ACTIVE</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<div class="modal" tabindex="-1" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Delete Session</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Delete Session <span></span>?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="deleteSession">Submit</button>
      </div>
    </div>
  </div>
</div>

JS

$('#deleteSession').click(function(event) {
    $.ajax({
        url: `/session/${userId}`,
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'JSON',
            data: {
            userId: userId,
            _method: "DELETE"
          },
        })
        .done(function(data) {
            $('#myModal').modal('hide');
            $('.alert.alert-success > span').text('Success');
            userId = "";

            $('#myModal').on('hide.bs.modal', function (e) {
              // Function does not run on first call 
              $(".alert.alert-success").show();
              getSessions();
            })
        })
        .fail(function() {
            console.log("error");
        })
});

What is the issue and how to fix it?

Upvotes: 1

Views: 3167

Answers (2)

rzlvmp
rzlvmp

Reputation: 9442

        .done(function(data) {
            // hide modal (before)
            $('#myModal').modal('hide');

            ...

            // register hide event listener (after)
            $('#myModal').on('hide.bs.modal', function (e) {
                ...
            })
        })

You hiding modal and after that adding hide action listener. Listener starts working after declaration, so it handles hide action just from second time.

And after that, when done occurs, you adding every time new listener for hide event without deleting old one.

I recommend to move $('#myModal').on('hide.bs.modal', ...}); outside done method (what means create listener only once, when page loaded).

  • EDIT1: working code sample
$( document ).ready(function() {

  // create event listener once when page loaded
  $('#myModal').on('hide.bs.modal', function (e) {
     $(".alert.alert-success").show();
     getSessions();
  });

  $('#deleteSession').click(function(event) {
    $.ajax({
        url: `/session/${userId}`,
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'JSON',
            data: {
            userId: userId,
            _method: "DELETE"
          },
        })
        .done(function(data) {
            $('#myModal').modal('hide');
            $('.alert.alert-success > span').text('Success');
            userId = "";

        })
        .fail(function() {
            console.log("error");
        })
  });
});

Jquery on 'event' don't runs operations inside of it, but register operations that will be ran when 'event' occurs.

Upvotes: 3

MuXeD
MuXeD

Reputation: 449

You could try success(function(data))

        success(function(data) {
            $('#myModal').modal('hide');
            $('.alert.alert-success > span').text('Success');
            userId = "";

            $('#myModal').on('hide.bs.modal', function (e) {
              // Function does not run on first call 
              $(".alert.alert-success").show();
              getSessions();
            })
        })

Or complete(function())

In the Oficial jQuery Doc.

Callback Function Queues

The beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.

I hope it works

Upvotes: 0

Related Questions