Put swal inside a js function

0

function excluiraluno(id){

  decisao = confirm('Deseja deletar?');

  if(decisao){
    $.ajax({ 
      url: "EditaExcluiAluno.php",
      dataType: "html",
      type: "POST",
      data: { id: id},

      success: function(data){
        $('#painelAbas').html(data);
      },

    });
  }
}

I want to put this swal inside this function but I can not do it

<!DOCTYPE html>
<html>

<head>
  <link data-require="sweet-alert@*" data-semver="0.4.2" rel="stylesheet" href="sweetalert.min.css" />
  <script src="sweetalert.min.js"></script>
   <link rel="stylesheet" type="text/css" href="styleExcluir.css"> 
</head>

<body>
  <form id="from1">
    <button>Excluir</button>
  </form>

  <script>
    document.querySelector('#from1').addEventListener('submit', function(e) {
      var form = this;

      e.preventDefault();

      swal({
          title: "Deseja Excluir?",
          icon: "warning",
          buttons: [
            'Cancelar',
            'Excluir'
          ],
          dangerMode: true,
        }).then(function(isConfirm) {
          if (isConfirm) {
            swal({
              title: 'Excluido com Sucesso!',
              timer: 2000,
              icon: 'success'
            }).then(function() {
              form.submit();
            });
          } else {
            swal("Cancelado com Sucesso", "", "success");
          }
        });
    });
  </script>


</body>

</html>
    
asked by anonymous 22.06.2018 / 01:11

1 answer

0

You are submitting the form, even canceling it before sending it. Now I would make a change in the code

  • I would add one more parameter to the delete student function, which would be a callback
  • Then after the if (isConfirm) would call the delete student function, the callback would be the swal that confirms the exclusion of the student.
  • And I would finally call this callback only if ajax returned the deletion message successfully. In the case after this code $('#painelAbas').html(data);

I have commented the code that is sending the form.

    <script>

    document.querySelector('#from1').addEventListener('submit', function(e) {
      var form = this;

      e.preventDefault();

      swal({
          title: "Deseja Excluir?",
          icon: "warning",
          buttons: [
            'Cancelar',
            'Excluir'
          ],
          dangerMode: true,
        }).then(function(isConfirm) {
          if (isConfirm) {
            excluiraluno(id);

            swal({
              title: 'Excluido com Sucesso!',
              timer: 2000,
              icon: 'success'
            }).then(function() {
               // form.submit(); voce tem que tirar esse form.submit() e adicionar a funcao
            });
          } else {
            swal("Cancelado com Sucesso", "", "success");
          }
        });
    });
  </script>
    
22.06.2018 / 01:49