简体   繁体   中英

Ajax form isn't submitted correctly

I am having this next issue with an Ajax form which is not submitted correctly. I have 3 forms, one for desktop, one for mobile, and a form which is located inside a modal. The first form for desktop version works perfectly and registers all data that I need through 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. 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. This is the Jquery code for the form which is working correctly.

   $('#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.

        //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 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:

      $('#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. This is the HTML markup of my modal's form. 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. 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:

   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. Therefore passing the new values through the ajax request, I was able to register my data to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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