Jim
Jim

Reputation: 35

How to detect the Cancel button in Sweetalert2

I'm using Sweetalert2 with an Ajax call.
I want to only show the error message after I click OK.

Currently, when clicking CANCEL or outside the modal, it will still do the Ajax call (and show error).

$(function() {
  $('.user-details').click(function(e) {
    e.preventDefault();
    Swal.fire({
      title: 'Are you sure?',
      text: '',
      icon: 'question',
      showCancelButton: true,
      showLoaderOnConfirm: true,
      reverseButtons: true,
      preConfirm: function() {
        console.log('AJAX request');
        return new Promise(function(resolve, reject) {
          setTimeout(function() {
            resolve();
          }, 1200);
        });
      },
    }).then(function() {
      Swal.fire({
        title: 'Error!',
        text: 'I want to show this, only after clicking OK!',
        icon: 'error',
        showCancelButton: false,
        showLoaderOnConfirm: false,
      });
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<button class='btn btn-success user-details'>View Details</button>

By clicking cancel or outside the modal, I want it to cancel without the "error" message.

Upvotes: 0

Views: 461

Answers (1)

RobertoAraneda
RobertoAraneda

Reputation: 11

Try this

    Swal.fire({
    title: 'titulo',
    text: 'text',
    icon: 'warning',
    showCancelButton: true,
    cancelButtonText: 'Cancelar',
    confirmButtonColor: '#00CC00',
    cancelButtonColor: '#999999',
    confirmButtonText: 'Si, Eliminar',
    reverseButtons: true,
}).then((result) => {
    if (result.isConfirmed) {
        $.ajax({
            type: 'POST', //or GET
            url: 'url',
            data: { id: id },
            success: (data, status, xhr) => {
                console.log(status);
         
            },
            error: (xhr, status, error) => {
                console.log('xhr', xhr);
                console.log('status', status);
                console.log('error', error);
            },
            dataType: 'json',
        });
    }
});

Upvotes: 1

Related Questions