Состояние AJAX с ошибкой не работает при неправильной отправке формы - PullRequest
0 голосов
/ 03 апреля 2019

У меня есть форма на HTML статической странице, использующая веб-сайт https://formcarry.com/ для работы и отправки без использования PHP.Я построил его с AJAX с spinner и toggleclass и appendtext, чтобы показать обратную связь, когда отправка была successful.У меня alert() при сбое отправки, проблема в том, что предупреждение не сработало, никогда не показывать его.Вы можете увидеть живой пример здесь .

Форма может не работать, когда:

  1. Пользователь не написал письмо.
  2. Пользовательне написал входное текстовое сообщение или имя. Пользователь не написал вводное текстовое сообщение или имя.
  3. Пользователь отправил несколько отправок, не дожидаясь более 15 секунд между ними.

Если это произойдет (форма завершится ошибкой), то будет показан только бесконечный счетчик, не отображено предупреждение.

HTML:

<form class="ajaxForm" action="https://formcarry.com/s/YN2IlAj4rfL" method="POST" accept-charset="UTF-8">
    <div class="form-group">
        <input type="email" class="form-control" id="email" aria-describedby="emailHelp" name="Correo" placeholder="Correo electrónico">
        <!-- use this to reply visitors and prevent spam via akismet -->
    </div>
    <div class="form-group">
        <input type="text" class="form-control" id="nombre" name="Nombre" placeholder="Nombre">
    </div>
    <div class="form-group">
        <textarea rows="4" class="form-control" id="textarea" name="Mensaje" placeholder="Cuéntanos"></textarea>
    </div>
    <input type="hidden" name="_gotcha">
    <!-- use this to prevent spam -->
    <div class="form-group">
        <input type="submit" class="btn-contacto float-right">
        <div class="spinner-border" role="status">
            <span class="sr-only">Cargando...</span>
        </div>
    </div>
</form>

CSS

.ajaxForm {
/* height: 297px; */
    width: 460px;
}
.form-control,
.form-control:active,
.form-control:hover,
.form-control:focus {
    border: 0px;
    margin-bottom: 6%;
    font-size: 1.05rem;
    border-radius: 0px;
    background: #c33e69;
    color: #fff;
}
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
    /* WebKit, Blink, Edge */
    color: rgba(255, 255, 255, 0.55) !important;
}
input:-moz-placeholder,
textarea:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: rgba(255, 255, 255, 0.55) !important;
    opacity: 1;
}
input::-moz-placeholder,
textarea::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: rgba(255, 255, 255, 0.55) !important;
    opacity: 1;
}
input:-ms-input-placeholder,
textarea:-ms-input-placeholder {
    /* Internet Explorer 10-11 */
    color: rgba(255, 255, 255, 0.55) !important;
}
input::-ms-input-placeholder,
textarea::-ms-input-placeholder {
    /* Microsoft Edge */
    color: rgba(255, 255, 255, 0.55) !important;
}
input::placeholder,
textarea::placeholder {
    /* Most modern browsers support this now. */
    color: rgba(255, 255, 255, 0.55) !important;
}
input.footer-input.footer-input::-webkit-input-placeholder,
textarea.footer-input::-webkit-input-placeholder {
    /* WebKit, Blink, Edge */
    color: rgb(195, 62, 105, 0.40) !important;
}
input.footer-input:-moz-placeholder,
textarea.footer-input:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: rgb(195, 62, 105, 0.40) !important;
    opacity: 1;
}
input.footer-input::-moz-placeholder,
textarea.footer-input::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: rgb(195, 62, 105, 0.40) !important;
    opacity: 1;
}
input.footer-input:-ms-input-placeholder,
textarea.footer-input:-ms-input-placeholder {
    /* Internet Explorer 10-11 */
    color: rgb(195, 62, 105, 0.40) !important;
}
input.footer-input::-ms-input-placeholder,
textarea.footer-input::-ms-input-placeholder {
    /* Microsoft Edge */
    color: rgb(195, 62, 105, 0.40) !important;
}
input.footer-input::placeholder,
textarea.footer-input::placeholder {
    /* Most modern browsers support this now. */
    color: rgb(195, 62, 105, 0.40) !important;
}
.btn-contacto {
    width: 100px;
    cursor: pointer;
    border: 2px #c33e69 solid;
    border-radius: 0px;
    color: #c33e69;
    background: #fff;
    height: 45px;
    padding: 0;
}
.spinner-border {
    display: none;
    float: right;
    margin-top: 1.5%;
    margin-right: 2.5%;
    color: #fbc00c;
}
/* Change the white to any color ;) */

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    -webkit-text-fill-color: #fff !important;
    -webkit-box-shadow: 0 0 0 30px #c33e69 inset !important;
}
/* Change the white to any color ;) */

input.footer-input:-webkit-autofill,
input.footer-input:-webkit-autofill:hover,
input.footer-input:-webkit-autofill:focus,
input.footer-input:-webkit-autofill:active {
    -webkit-text-fill-color: #c33e69 !important;
    -webkit-box-shadow: 0 0 0 30px #fff inset !important;
}
.ajaxForm {
    -webkit-transition: opacity 0.3s ease-in-out;
    -moz-transition: opacity 0.3s ease-in-out;
    -ms-transition: opacity 0.3s ease-in-out;
    -o-transition: opacity 0.3s ease-in-out;
    opacity: 1;
}
.has-success {
    opacity: 0;
}

JS

$(function() {
    $(".ajaxForm").submit(function(e) {
        $('.spinner-border').css("display", "block");
        e.preventDefault();
        var href = $(this).attr("action");
        $.ajax({
            type: "POST",
            dataType: "json",
            url: href,
            data: $(this).serialize(),
            success: function(response) {
                if (response.status == "success") {
                    $(".ajaxForm").toggleClass("has-success");
                    setTimeout(function() {
                        $(".ajaxForm").html(response);
                        $(".ajaxForm").toggleClass("has-success").append("<div class='swal2-icon swal2-success swal2-animate-success-icon' style='display: flex;'><div class='swal2-success-circular-line-left' style='background-color: rgb(255, 255, 255);'></div><span class='swal2-success-line-tip'></span><span class='swal2-success-line-long'></span><div class='swal2-success-ring'></div> <div class='swal2-success-fix' style='background-color: rgb(255, 255, 255);'></div><div class='swal2-success-circular-line-right' style='background-color: rgb(255, 255, 255);'></div></div><p class='text-center'>¡Gracias! Contactaremos contigo lo antes posible.</p>");
                    }, 500);
                } else {
                    alert("An error occured.");
                }
            }
        });
    });
});

1 Ответ

1 голос
/ 03 апреля 2019

Вы должны использовать функцию обратного вызова для обработки ошибок API.Вы можете прочитать об этом здесь .

$.ajax({
    type: "POST",
    dataType: "json",
    url: href,
    data: $(this).serialize(),
    success: function(response){
    //This function triggers only if the request succeeds
        if(response.status == "success"){

        }else{

        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
         //Function triggers when API call fails
    }       
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...