简体   繁体   English

Ajax 表单未正确提交

[英]Ajax form isn't submitted correctly

I am having this next issue with an Ajax form which is not submitted correctly.我遇到了一个未正确提交的 Ajax 表单的下一个问题。 I have 3 forms, one for desktop, one for mobile, and a form which is located inside a modal.我有 3 个 forms,一个用于台式机,一个用于移动设备,以及一个位于模式内的表单。 The first form for desktop version works perfectly and registers all data that I need through Cakephp.桌面版的第一个表单完美运行,并通过 Cakephp 注册了我需要的所有数据。 The second one, which is for the mobile version displays an error which is coming from a function I developed for error handling with Jquery.第二个,用于移动版本,显示来自 function 的错误,我为使用 Jquery 开发的错误处理。 Both the mobile-version form and the modal form are appearing to have the same problem.移动版表单和模态表单似乎都存在同样的问题。 I send the query through ajax, but the problem persists in displaying the same error.我通过 ajax 发送查询,但问题仍然存在,显示相同的错误。 This is the Jquery code for the form which is working correctly.这是正常工作的表单的 Jquery 代码。

   $('#nueva_normalidad_form').on('submit', function(e){
    e.preventDefault();
    $('#errorMain').html('');
    var formContainer = $('#form_container');
    var errorArea = $('#errorMain');
    if(!validateDocApplication(errorArea)){
        return;
    }
    var data = $('#nueva_normalidad_form').serialize();

    var beforeSend = function () {
        $('#sendDataButton').attr("disabled", true);
    };
    var error = function (a) {
        $('#errorMain').html('<div class="alert alert-danger">' + info.txt + '</div>');
        return a;
    };

    var success = function(info) {
        info = $.parseJSON(info);
        if (info.id === 200) {
            formContainer.animate({
                display: "none"
            }, {
                duration: 600,
                complete: function () {
                    formContainer.css("display", "none");
                    $('div#successText').css("display", "block");
                }
            });
            $('#successText').animate({
                display: "block"
            }, {duration: 700,
                complete: function () {
                    $('#successText').css("display", "block");
                }
            });
            dataLayer.push({'eventcategory': 'Conversion', 'event': 'submitForm'});
        } else {
            $('#errorMain').html('<div class="alert alert-danger">' + error.txt + '</div>');
        }
    };
    saveNewNormDoctor(data, beforeSend, success, error);
});

This is the function for the error handling of the field inputs.这是用于现场输入错误处理的 function。

        //Validates the field inputs of Desktop Form
function validateDocApplication(errorArea) {
    var noError = true;
    if(!$('input[name="name"]').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el nombre</div>');
        noError = false;
    }

    if(!$('input[name="surname"]').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el apellido</div>');
        noError = false;
    }

    if(!$('input[name="email"]').val()){
        noError = false;
        errorArea.html('<div class="alert alert-danger">Por favor, inserte su correo</div>');
    }else{
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        noError = re.test($('input[name="email"]').val());
    }

    if(!$('input[name="phone"]').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de teléfono</div>');
        noError = false;
    }

    if(!$('input[name="colegiado"]').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
        noError = false;
    }

    var valorSpec = $('#spec option:selected').val();
    if(!valorSpec){
        errorArea.html('<div class="alert alert-danger">Seleccione una especialidad</div>');
        noError = false;
    }

    return noError;
}

This is the function which sends the request and saves the data to the database.这是发送请求并将数据保存到数据库的 function。

   function saveNewNormDoctor(data, beforeSend, success, error) {
   $.ajax({
       type: "POST",
       url: "/staticpages/save_doc_new_norm",
       data: data,
       beforeSend: beforeSend,
       success: success,
       error: error
   });
}

For my modal-version form I am using this submit function:对于我的模态版本表单,我正在使用此提交 function:

      $('#sendDataNewNorm').on('submit', function (e) {
        e.preventDefault();
        $('#errorModal').html('');
        var errorArea = $('#errorModal');
        var formContainer = $('#formNewnorm');
        var successArea = $('#successTextModal');
        if(!validateDocApplication(errorArea)){
            return;
        }

        var data = $('#sendDataNewNorm').serialize();
        var beforeSend = function () {
            $('#sendDataNewNormButton').attr("disabled", true);
        };

        var error = function (a) {
            errorArea.html('<div class="alert alert-danger">' + info.txt + '</div>');
            return a;
        };

        var success = function (info) {
            info = $.parseJSON(info);
            if (info.id === 200) {
                formContainer.animate({
                    display: "none"
                }, {
                    duration: 600,
                    complete: function () {
                        formContainer.css("display", "none");
                        successArea.css("display", "block");
                    }
                });
                successArea.animate({
                    display: "block"
                }, {duration: 700,
                    complete: function () {
                        successArea.css("display", "block");
                    }
                });
            } else {
                errorArea.html('<div class="alert alert-danger">' + info.txt + '</div>');
            }
        };
    saveNewNormDoctor(data, beforeSend, success, error);
});

All inputs in 3 forms have the same name attributes such as name , surname , email , phone , colegiado and the value that it gets through the #spec select element. 3 forms 中的所有输入都具有相同的名称属性,例如namesurnameemailphonecolegiado以及它通过#spec Z99938282F04071859941E18F16EF 元素获得的值。 This is the HTML markup of my modal's form.这是我的模态表单的 HTML 标记。 The same thing occurs in my mobile-version form.同样的事情也发生在我的移动版表单中。 I am at a dead-end.我处于死胡同。 My Cakephp function for the server-side process is correct as my main form is being submitted correctly.我的服务器端进程的 Cakephp function 是正确的,因为我的主表单已正确提交。 Any hint on how to resolve the problem would be appreciating.任何有关如何解决问题的提示都将不胜感激。 The error is this one.错误就是这个。 While in the other form I always get all values correctly, in this ones, every one of these values come up empty.在另一种形式中,我总是正确地获得所有值,而在这种形式中,这些值中的每一个都是空的。

 errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');

在此处输入图像描述

Thanks you.谢谢。

            <form id="sendDataNewNorm">
                    <div class="text-centers">
                        <h4 class="h4 font_Conv_Roboto-Regular text-center top_margin"> 
                            <?= __('Rellene el siguiente formulario <br>y nos pondremos en contacto con usted.'); ?>
                        </h4>
                    </div>
                    <div id="formNewnorm" class="bottom_margin">                                                           
                            <div class="col-md-12 col-sm-12 form-group top_margin no_side_paddings">
                                <div class="col-sm-6 col-md-6 no_padding_left">
                                    <input name="name" id="name" class="desesc form-control" type="text"  placeholder="<?= __('Nombre'); ?> *">
                                </div>
                                <div class="col-sm-6 col-md-6 no_side_paddings">
                                    <input name="surname" id="surname" class="desesc form-control" type="text"  placeholder="<?= __('Apellidos'); ?> *">
                                </div>
                            </div>
                            <div class="form-group">
                                <input name="email" id="email" class="desesc form-control" type="email" placeholder="<?= __('e-mail');?> *">
                            </div>
                            <div class="form-group">
                                <input name="phone" id="tel" class="desesc form-control" type="number" placeholder="<?= __('Número de contacto');?> *">
                            </div>
                            <div class="form-group">
                                <select class="desesc form-control" name="especialidad" id="spec">
                                    <option value="0"><?= __('Seleccione su especialidad'); ?></option>
                                    <?php foreach ($specs AS $k => $v) { ?>
                                        <option value="<?= $k; ?>"><?= $v; ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <input name="colegiado" id="collegiate" class="desesc form-control" type="text" placeholder="<?= __('Número de colegiado'); ?> *">
                            </div>
                        <div class="form-group">
                            <div class="radio radio_highlight">
                                <input type="radio" name="condiciones" id="condiciones_1" value="1" required="">
                                <label class="text-primary" for="condiciones_1">
                                   <?= __('He leído y acepto las');?> <a target="_blank" href="http://topdoctors.local/terminos-legales">
                                        <u><?= __('Condiciones de Uso'); ?></u></a>
                                </label>                                        
                            </div>
                            <input type="hidden" name="created" value="<?php echo date('Y-m-d'); ?>" >
                        </div>
                        <div class="form-group">
                            <div id="errorModal"></div>                                                            
                            <button id="sendDataButton" class="btn btn-block btn-primary btn_md">
                                <?= __('Solicitar información'); ?>
                            </button>
                        </div>  
                    </div>
                    <div id="successTextModal" class="top_margin_md bottom_margin_md top_padding_md bottom_padding bg_light text-center" style="display:none;">
                            <img class="top_padding_md img-responsive" src="/css/quironsalud/check.png" style="margin: 0 auto" />
                            <div class="box-success top_padding_md bottom_padding_md">
                                <span class="top_margin text-success font_Conv_Roboto-Regular ">
                                  <?=  __('Tu solicitud ha sido enviada correctamente'); ?>
                                 </span>
                            </div>
                    </div>
                </form>

Finally, I found the solution to my problem.最后,我找到了解决问题的方法。 By assigning new ids for every input field which I needed, I came to this function:通过为我需要的每个输入字段分配新的 id,我来到了这个 function:

   function validateDocApplicationForm(errorArea) {
    var noError = true;

    if(!$('#name_form').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el nombre</div>');
        noError = false;
    } else {
        name = $('#name_form').val();
        return name;
    }


    if(!$('#surname_form').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el apellido</div>');
        noError = false;
    } else {
        surname = $('#surname_form').val();
        return surname;
    }

    if(!$('#email_form').val()){
        noError = false;
        errorArea.html('<div class="alert alert-danger">Por favor, inserte su correo</div>');
    } else {
        email = $('#email_form').val();

        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        noError = re.test(email);
        return email;
    }

    if(!$('#tel_form ').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de teléfono</div>');
        noError = false;
    }else {
        phone = $('#tel_form').val();
        return phone;

    }

    if(!$('#collegiate_form').val()){
        errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
        noError = false;
    } else {
        colegiado = $('#collegiate_form').val();
        return colegiado;
    }

    var valorSpec = $('#spec_form option:selected').val();
    if(!valorSpec){
        errorArea.html('<div class="alert alert-danger">Seleccione una especialidad</div>');
        noError = false;
    } 
    return noError;
}

The changes I had to make on my markup were these:我必须对标记进行的更改如下:

               <div id="formNewnorm" class="bottom_margin">                                                           
                            <div class="col-md-12 col-sm-12 form-group top_margin no_side_paddings">
                                <div class="col-sm-6 col-md-6 no_padding_left">
                                    <input name="name" id="name_form" class="desesc form-control" type="text"  placeholder="<?= __('Nombre'); ?> *">
                                </div>
                                <div class="col-sm-6 col-md-6 no_side_paddings">
                                    <input name="surname" id="surname_form" class="desesc form-control" type="text"  placeholder="<?= __('Apellidos'); ?> *">
                                </div>
                            </div>
                            <div class="form-group">
                                <input name="email" id="email_form" class="desesc form-control" type="email" placeholder="<?= __('e-mail');?> *">
                            </div>
                            <div class="form-group">
                                <input name="phone" id="tel_form" class="desesc form-control" type="number" placeholder="<?= __('Número de contacto');?> *">
                            </div>
                            <div class="form-group">
                                <select class="desesc form-control" name="especialidad" id="spec_form">
                                    <option value="0"><?= __('Seleccione su especialidad'); ?></option>
                                    <?php foreach ($specs AS $k => $v) { ?>
                                        <option value="<?= $k; ?>"><?= $v; ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <input name="colegiado" id="collegiate_form" class="desesc form-control" type="number" placeholder="<?= __('Número de colegiado'); ?> *">
                            </div>
                        <div class="form-group">
                            <div class="radio radio_highlight">
                                <input type="radio" name="condiciones_form" id="condiciones_form" value="1" required="">
                                <label class="text-primary" for="condiciones_form">
                                   <?= __('He leído y acepto las');?> <a target="_blank" href="http://topdoctors.local/terminos-legales">
                                        <u><?= __('Condiciones de Uso'); ?></u></a>
                                </label>                                        
                            </div>
                            <input type="hidden" name="created" value="<?php echo date('Y-m-d H:i:s'); ?>" >
                        </div>
                        <div class="form-group">
                            <div id="errorModal"></div>                                                            
                            <button id="sendDataButton" class="btn btn-block btn-primary btn_md">
                                <?= __('Solicitar información'); ?>
                            </button>
                        </div>  
                    </div>

With this approach, I was able to re-assign the values to every input with each respective name and new id.使用这种方法,我能够使用各自的名称和新 ID 将值重新分配给每个输入。 Therefore passing the new values through the ajax request, I was able to register my data to the database.因此,通过 ajax 请求传递新值,我能够将我的数据注册到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM