web-dev-qa-db-fra.com

SweetAlert confirme avec la demande Ajax

Je suis nouveau sur Javascript - le codant pour la première fois. J'essaie de créer un bouton avec confirmation de suppression avec SweetAlert . Rien ne se passe lorsque j'appuie sur le bouton avec onclick="confirmDelete()". Ce code n'est peut-être que du crabe, mais le voici:

<script type="text/javascript">
    function confirmDelete() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        )},
            $.ajax({
                url: "scriptDelete.php",
                type: "POST",
                data: {id: 5},
                dataType: "html",
                success: function () {
                    swal("Done!","It was succesfully deleted!","success");
                }
            });
    }
</script>

<a href="#" onclick="confirmDelete()">Delete</a>

Puis-je ajouter une alerte si la suppression échoue?

5
lingo

Si je comprends bien votre question, vous demandez comment gérer une condition d'erreur dans une demande ajax. Les paramètres Ajax ont un attribut d'erreur qui peut être utilisé comme ceci 

$.ajax({
  .... other settings you already have
  error: function (xhr, ajaxOptions, thrownError) {
    swal("Error deleting!", "Please try again", "error");
  }
});

En outre, vous invoquez swal de manière erronée. Swal a un rappel comme celui-ci 

swal({settings}, function(isConfirm){});

Le code global ressemblerait à quelque chose comme ça

function confirmDelete() {
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }, function (isConfirm) {
        if (!isConfirm) return;
        $.ajax({
            url: "scriptDelete.php",
            type: "POST",
            data: {
                id: 5
            },
            dataType: "html",
            success: function () {
                swal("Done!", "It was succesfully deleted!", "success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                swal("Error deleting!", "Please try again", "error");
            }
        });
    });
}

Voici une démohttp://jsfiddle.net/dhirajbodicherla/xe096w10/33/

11
Dhiraj

Essayez ce code.Il fonctionne bien pour moi.

$('.delete-confirm').on('click', function() {
    var postID = $(this).val();
    console.log(postID);
    swal({
        title: "Are you sure?",
        text: "If you delete this post all associated comments also deleted permanently.",
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes, delete it!",
    }, function() {
        setTimeout(function() {
            $.post("delete.php", {
                    id: postID
                },
                function(data, status) {
                    swal({
                            title: "Deleted!",
                            text: "Your post has been deleted.",
                            type: "success"
                        },
                        function() {
                            location.reload();
                        }
                    );
                }
            );

        }, 50);
    });
});
3
Faisal

J'ai finalement réussi à faire fonctionner ce mec dans 3 ans.

function dropConfig(config_index){

  swal({
   title: "WARNING:", 
   text: "Are you sure you want to delete this connection?", 
   type: "warning",
   inputType: "submit",
   showCancelButton: true,
   closeOnConfirm: true,
   timer: 2000
       }, //end swal   }


function(isConfirm) {
      if (isConfirm == true) {

         //do the ajax stuff.
         $.ajax({
            method: "POST",
            url: "/drop_config",
            data: {"curr_config":  $("#curr_conf_conn_name_" + config_index).val()}})
           .success(function(msg) {
           show_notification(msg,"success");
           setInterval(function() {.reload();
           }, 2500);})
           .error(function(msg) {show_notification(msg.responseText,"danger");});




      } // end if }
   }); //  end function } & end swal )
}     //   end function }
2
Kevin S

Vous avez fait une erreur dans swal({)} il devrait être swal({})

Code mis à jour:

<script type="text/javascript">
    function confirmDelete() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        },
         function(isConfirm){
           if (isConfirm) {
            $.ajax({
                url: "scriptDelete.php",
                type: "POST",
                data: {id: 5},
                dataType: "html",
                success: function () {
                    swal("Done!","It was succesfully deleted!","success");
                }
            });
          }else{
                swal("Cancelled", "Your imaginary file is safe :)", "error");
          } 
       })
    }
</script>
1
Bhavin Solanki