Подтверждение Sweet Alert 2 перед отправкой

Я пытаюсь сделать всплывающее окно подтверждения перед отправкой формы. Но это не работает. Я использую Sweet Alert 2.

document.querySelector('#order').addEventListener('submit', function(e) {
        var form = $(this).parents('form');
        e.preventDefault();
        swal({
            title: "Are you sure?",
            text: "Once a invoice is created, you will not be able to delete without the help of support",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: '#DD6B55',
            confirmButtonText: 'Yes, I am sure!',
            cancelButtonText: "No, cancel it!",
        }).then(function() {
            swal({
                title: 'Success!', 
                text: 'Invoice created! Go to the invoice tab to pay it.', 
                type: 'success'
            }, function() {
                form.submit();
            });
        },function(dismiss) {
            if(dismiss == 'cancel') {
                swal("Cancelled", "Invoice not created!", "error");
            }
        });
    });

Это мой код Javascript, и мой код PHP выглядит примерно так

 <?php
if(isset($_POST['k'])
{
header('Location: https://google.com');
}
?>

Мой HTML-код

<form method="POST">
<button type="submit" name="k"></button
</form>

Не работает почему?


Обновлять

$("#order").on('submit', function(e) {
        var form = $(this);
        e.preventDefault();
        swal({
            title: "Are you sure?",
            text: "Once a invoice is created, you will not be able to delete without the help of support",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: '#DD6B55',
            confirmButtonText: 'Yes, I am sure!',
            cancelButtonText: "No, cancel it!",
        }).then(function() {
            swal({
                title: 'Success!', 
                text: 'Invoice created! Go to the invoice tab to pay it.', 
                type: 'success'
            }, function() {
                $(this).trigger('submit');
            });
        },function(dismiss) {
            if(dismiss == 'cancel') {
                swal("Cancelled", "Invoice not created!", "error");
            }
        });
    });

Также я забыл добавить, что я проанализировал этот код, и в моем фактическом коде есть есть идентификатор в форме

Под неработающим я подразумеваю, что данные не публикуются. Если он работает правильно, он должен перенаправлять на google.com в соответствии с кодом PHP.


person Alex Rieker    schedule 26.10.2016    source источник
comment
Определить не работает.   -  person ceejayoz    schedule 26.10.2016


Ответы (2)


Я не кодер, но обнаружил, что размещение отправки под .then(function() { было для меня рабочим решением. Я использовал код lp.jQuery("div.main-form form").submit(); но ваше имя формы будет другим. Я надеюсь, что это поможет в некотором роде.

$("#order").on('submit', function(e) {
    var form = $(this);
    e.preventDefault();
    swal({
        title: "Are you sure?",
        text: "Once a invoice is created, you will not be able to delete without the help of support",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: 'Yes, I am sure!',
        cancelButtonText: "No, cancel it!",
    }).then(function() {
      $(this).trigger('submit');
        swal({
            title: 'Success!', 
            text: 'Invoice created! Go to the invoice tab to pay it.', 
            type: 'success'
        }, function() {
            $(this).trigger('submit');
        });
    },function(dismiss) {
        if(dismiss == 'cancel') {
            swal("Cancelled", "Invoice not created!", "error");
        }
    });
});
person Vin    schedule 11.05.2017

Во-первых, в этом HTML нет селектора #order.

Во-вторых, вы захотите предотвратить поведение элемента формы по умолчанию, поэтому сделайте следующее:

$("form").on('submit', function(e) {
    var form = $(this);
    e.preventDefault();
    //[...]

Затем, где вы хотите, наконец, представить, вы можете поместить это:

$(this).trigger('submit');
person Phiter    schedule 26.10.2016
comment
Извините, я забыл сказать, что проанализировал фактический код в моем фактическом коде, идентификатор в элементе формы есть. Пожалуйста, проверьте мое обновление - person Alex Rieker; 26.10.2016