Показывать SweetAlert в функции удаления php - PullRequest
0 голосов
/ 20 марта 2019

Я пытаюсь показать сладкое оповещение в своем DELETE FEATURE, но, к сожалению, мой код сейчас не работает. Я уже ищу похожую функцию, но вижу некоторые, но это не помогло мне подумать. Вот мой код

 <a id="<?php echo $id;?>" value="<?php echo $id;?>"  name="delete"   onclick="archiveFunction(this.id)">
                        <i class="glyphicon glyphicon-trash text-red"></i></a>

И это мой запрос AJAX

 $(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();   
});
$('#reloadpage').click(function() {

    location.reload(true);
});
function archiveFunction(id) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
        swal({
  title: "Are you sure?",
  text: "But you will still be able to retrieve this file.",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, Delete it!",
  cancelButtonText: "No, cancel please!",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(isConfirm){
  if (isConfirm) {
    // this is `post` request to the server
    // so you can get the data from $_POST variables, says $_POST['delete'] $_POST['v_id']
    $.ajax({
        method: 'POST',
        data: {'delete': true, 'id' : id },
        url: 'user_del.php',
        success: function(data) {

        }
    });
    swal("Updated!", "Your imaginary file has been Deleted.", "success");

} else {
    swal("Cancelled", "Your file is safe :)", "error");
}

А это мой архивный запрос. Не беспокойтесь о моем запросе. Я установил статус 0, чтобы архивировать одни данные, и он перейдет на страницу архива. Я просто хочу отобразить СЛАДКОЕ ПРЕДУПРЕЖДЕНИЕ, когда я удаляю данные или архивирую их. Заранее спасибо.

 <?php session_start();
if(empty($_SESSION['id'])):
header('Location:../index');
endif;
include("../dist/includes/dbcon.php");
$id=$_REQUEST['id'];
$result=mysqli_query($con,"UPDATE accounts_at SET status = 0 WHERE id ='$id'")
    or die(mysqli_error());
        if ($result !== false) {
 echo "<script type='text/javascript'>alert('Successfully deleted a account!');</script>";
    echo "<script>document.location='index'</script>";
    }

?>

Ответы [ 2 ]

0 голосов
/ 20 марта 2019

попробуйте это:

function archiveFunction(id) {
    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: "delete.php",
            type: "POST",
            data: {
                id: id
            },
            dataType: "html",
            success: function () {
                swal("Done!", "It was succesfully deleted!", "success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                swal("Error deleting!", "Please try again", "error");
            }
        });
    });
}
0 голосов
/ 20 марта 2019

Ваше предупреждение ОБНОВЛЕНО не в том месте, если вы хотите, чтобы оно запускалось после того, как объект был официально удален на сервере.

function(isConfirm){
 if (isConfirm) {
// this is `post` request to the server
 $.ajax({
    method: 'POST',
    data: {'delete': true, 'id' : id },
    url: 'user_del.php',
    success: function(data) { 
       //if you put it here it will run after the file is deleted
      swal("Updated!", "Your imaginary file has been Deleted.", "success");
    }
})
//if you put it here it will run before and even if your file is not deleted
// swal("Updated!", "Your imaginary file has been Deleted.", "success");

} else {
    swal("Cancelled", "Your file is safe :)", "error");
}

Откройте консоль разработки в вашем веб-браузере. Это дает вам какие-либо ошибки? Вы вообще получаете какие-либо оповещения?

...