Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - Issues with swal destroy function

I have the swal function working code but when i click cancel without doing, it is going into ajax call which i do not want to

$(document).on('click','.addon',function() {
    Swal.fire({
      title: 'Provide Your Email Address',
      html: `<input type="email" name="emailaddress" id="emailaddress">
      `,
      confirmButtonText: 'Yes',
      showCancelButton:true,
      focusConfirm: false,
      allowOutsideClick:false,
      preConfirm: () => {
        const emailaddress = Swal.getPopup().querySelector('#emailaddress').value;
        if (!emailIsValid(emailaddress)) {
          Swal.showValidationMessage(`Please enter correct Email`)
        }
        return { emailaddress: emailaddress }
      },
      didDestroy: () => {
        $(this).prop('checked',false);
        return; - if i cancel, it should just quit and not go into tthen, 
      }
    }).then((result) => {
        var data = 'emailaddress=' + Swal.getPopup().querySelector('#emailaddress').value
        $.ajax({
          url: 'submission.cfm',
          data: data,
          type: 'POST',
          success: function(data) {
              var sdata = jQuery.parseJSON(data);
              if($.trim(sdata.status) == 1) {
                  swal.fire({
                      title:"Cool",
                      text: sdata.message,
                      type:"success",
                      confirmButtonText: 'OK'
                  }).then(() => {
                      window.location.reload();
                  });
              }else {
                  var err = sdata.message;
                  swal.fire("Oops...", err, "error");
              }
          }
      });
    })
  });

the above code works but when i click cancel, it still goes into the ajax then, but i do not want it to go there, am i missing anything

question from:https://stackoverflow.com/questions/65866442/issues-with-swal-destroy-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

https://sweetalert2.github.io/#showCancelButton seems to document what you need:

When an alert is dismissed by the user, the Promise returned by Swal.fire() will be resolved with an object { isDismissed: true, dismiss: reason } documenting the reason it was dismissed: ...

So it seems you need to handle it in the resolver (then):

}).then((result) => {
   if (result.isDismissed) {
     return;
   } else {
       var data = 'emailaddress=' + Swal.getPopup().querySelector('#emailaddress').value
       $.ajax({ ...
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...