Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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',
        });
    }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!