данные отправляются даже при нажатии кнопки отмены в sweetalert2 - PullRequest
0 голосов
/ 19 октября 2018

Я смог отправить данные при нажатии кнопки подтверждения.
однако, когда нажата кнопка отмены sweetalert2 показывает, как успешно вставил данные.
назад-end показывает как пустую строку. (в таблице базы данных)
, как проверить, когда я нажал кнопку отмены, чтобы не отправлять данные на сервер.


Javascript function

    function inputPass(complaintID) { // complaint id pass is ok.
    swal({
        text: 'Input comment message',
        input: 'textarea',
        showCancelButton: true,
    }).then(function(sample_text) { 
        console.log(sample_text);
        if(sample_text === '') { // problem is here.
            swal({
                type: 'warning',
                html: 'cannot proceed without input'
            });
        } else {
            console.log(sample_text);
            $.ajax({
                type: "POST",
                url: "../ajax/ajax_active_deact.php?type=complaint_answered",
                data: {complaintID: complaintID, sampleText: sample_text}
            }).done(function (res) {
                if(!res) {
                    swal({
                        type: 'error',
                        html: 'insert the valid text'
                    });
                } else {
                    swal({
                        title: 'done',
                        text: 'all right',
                        type: 'success',
                        allowOutsideClick: false,
                        confirmButtonText: 'Ok'
                    });
                }
            });
        }
    });
}

php ajax code

function complaint_answered() {
    include_once('../backend/ConsumerComplaint.php');
    $con_complaint = new ConsumerComplaint();
    $res = $con_complaint>mark_as_answered($_POST['complaintID'],$_POST['sampleText']);
    echo $res;
}

Это моя функция класса

    function mark_as_answered($id, $comment) {
    //var_dump($comment);
    $val = $comment['value']; // $comment is a associative array, with the key of 'value'
    $sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val' 
            WHERE  complaint_id = '$id' ";
    $res = $this->conn->query($sql);
    return $res;
}

  • изображение, когда я нажимал кнопку отмены на сетевой панели в хроме enter image description here

  • изображение консоли enter image description here

  • изображение данных поста в хроме enter image description here

Я новичок в разработкеи не могу обойти, как решить эту проблему.пожалуйста, кто-нибудь может дать мне то, что я делаю не так здесь.Thnks!

Ответы [ 2 ]

0 голосов
/ 19 октября 2018

Вы получите result.value, только если пользователь нажал Ok, чтобы вы могли проверить, есть ли значение, и если оно пустое, вы увидите свое сообщение об ошибке.Если значение отсутствует, ничего не происходит.

Фрагмент:

    swal({
        text: 'Input comment message',
        input: 'textarea',
        showCancelButton: true,
    }).then(function(result) {
        if(result.value) {
            $.ajax({
                type: "POST",
                url: "../ajax/ajax_active_deact.php?type=complaint_answered",
                data: {complaintID: complaintID, sampleText: result.value}
            }).done(function (res) {
                if(!res) {
                    swal({
                        type: 'error',
                        html: 'insert the valid text'
                    });
                } else {
                    swal({
                        title: 'done',
                        text: 'all right',
                        type: 'success',
                        allowOutsideClick: false,
                        confirmButtonText: 'Ok'
                    });
                }
            });
        } else if (result.value === "") {
            swal({
                type: 'warning',
                html: 'cannot proceed without input'
            });
        }
    });
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@7.28.7/dist/sweetalert2.all.min.js"></script>

Ваш класс:

В вашем php ajax-коде вы передаете $_POST['sampleText'] это не массив, а строка, поэтому $comment['value'] не будет содержать текст.

function mark_as_answered($id, $comment) {
    //var_dump($comment);
    $val = $comment;
    $sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val' 
            WHERE  complaint_id = '$id' ";
    $res = $this->conn->query($sql);
    return $res;
} 

PS: Пожалуйста, ознакомьтесь с SQL-инъекцией , чтобы люди не могли внедрить вредоносный код вваши SQL-запросы.

0 голосов
/ 19 октября 2018

Похоже, что образец текста всегда установлен в массив.Я бы попробовал изменить оператор if

if(sample_text === '') { // problem is here.
            swal({
                type: 'warning',
                html: 'cannot proceed without input'
            });
        } else {
            console.log(sample_text);

на что-то вроде

if(sample_text['dismiss'] == 'cancel') { // problem is here.
        swal({
            type: 'warning',
            html: 'cannot proceed without input'
        });
    } else {
        console.log(sample_text);
...