简体   繁体   中英

Form submitting multiple times when created dynamically using AJAX/jQuery

I'm using Google Maps API in a project, and the infoWindow content is built dynamically, so i cant use document ready function to assign the validator to the form.

I'm using, bootstrap, bootstrapValidator and jQuery.

I created a function, and the submit button call it, in the first click, ok, 1 call, second click, 2 calls, 3calls, 4 calls, etc...

What i need to do, to the Submit only be called only once?

THIS ONLY HAPPENS WITH THE DYNAMICALLY CONTENT, the static forms have a normal behavior.

Here's the code, take a look please.

Here's the content that creates on fly:

var content_string = '<div class="scrollFix"> <div id="divinfowindow"> <div class="container-fluid container-fluid-corrige"></div> <div class="row"> <div class="col-sm-3 img-corrige-60"> <img src="http://placehold.it/60x60" class="img-rounded"/> </div> <div class="col-sm-9 text-corrige"> <p>Por: Russell Bega</p> <p>Em: </p> <p class="white-space-normal">endereco</p> </div> </div> <form class="form-horizontal" role="form" id="formNovaMarcacao" action="/novaMarcacao"> <div class="form-group"> <div class="col-sm-12"> <input type="text" class="form-control" id="inputTituloNovaMarc" name="inputTituloNovaMarc" placeholder="Titulo"> </div> </div> <div class="form-group"> <div class="col-sm-12"> <select id="inputCategoriaNovaMarc" name="inputCategoriaNovaMarc" class="form-control select-corrige"> <option>Escolha uma categoria</option> </select> </div> </div> <div class="form-group"> <div class="col-sm-12"> <select id="inputSubCategoriaNovaMarc" name="inputSubCategoriaNovaMarc"class="form-control select-corrige"> <option>Escolha uma categoria</option> </select> </div> </div> <div class="form-group"> <div class="col-sm-12"> <textarea class="form-control" id="inputDescricaoNovaMarc" name="inputDescricaoNovaMarc" rows="3" placeholder="Descricao"></textarea> </div> </div> <div class="form-group"> <div class="pull-right"> <button type="submit" id="btnNovaMarc" onclick="validaNovaMarcacao()" name="btnNovaMarc" class="btn btn-default" data-loading-text="Postando...">Postar</button> </div> </div> </form> <div id="statusNovaMarc"></div> </div> </div>';

And here's the validator code:

function validaNovaMarcacao(){
    $('#formNovaMarcacao').bootstrapValidator({ 
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        container: 'tooltip',
        submitButtons: btnNovaMarc,
        fields: {
            inputTituloNovaMarc: {
                validators: {
                    notEmpty: {
                        message: 'Este campo não pode ser vazio.'
                    }
                }
            }
        }
    })
.on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();

                var dados = {
                    inputTituloNovaMarc : $("#inputTituloNovaMarc").val(),
                };

                var formURL = $(this).attr("action");

                //console.log(dados);
                $('#btnNovaMarc').button('loading');

                jQuery.ajax({
                    type: "POST",
                    dataType: "json",
                    url: formURL,
                    data: dados,
                    success: function( data )
                    {
                        alert("ok" + data);

                    },
                    error : function (data){
                    }
                });

                $('#btnNovaMarc').button('reset');
            return false;
            });
}

Here's the content string indented:

<div class="scrollFix">
    <div id="divinfowindow">
        <div class="container-fluid container-fluid-corrige"></div>
        <div class="row">
            <div class="col-sm-3 img-corrige-60"> <img src="http://placehold.it/60x60" class="img-rounded"/> </div>
            <div class="col-sm-9 text-corrige">
                <p>Por: Russell Bega</p>
                <p>Em: </p>
                <p class="white-space-normal">endereco</p>
            </div>
        </div>
        <form class="form-horizontal" role="form" id="formNovaMarcacao" action="/novaMarcacao">
            <div class="form-group">
                <div class="col-sm-12"> <input type="text" class="form-control" id="inputTituloNovaMarc" name="inputTituloNovaMarc" placeholder="Titulo"> </div>
            </div>
            <div class="form-group">
                <div class="col-sm-12">
                    <select id="inputCategoriaNovaMarc" name="inputCategoriaNovaMarc" class="form-control select-corrige">
                        <option>Escolha uma categoria</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-12">
                    <select id="inputSubCategoriaNovaMarc" name="inputSubCategoriaNovaMarc"class="form-control select-corrige">
                        <option>Escolha uma categoria</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-12"> <textarea class="form-control" id="inputDescricaoNovaMarc" name="inputDescricaoNovaMarc" rows="3" placeholder="Descricao"></textarea> </div>
            </div>
            <div class="form-group">
                <div class="pull-right"> <button type="submit" id="btnNovaMarc" onclick="validaNovaMarcacao()" name="btnNovaMarc" class="btn btn-default" data-loading-text="Postando...">Postar</button> </div>
            </div>
        </form>
        <div id="statusNovaMarc"></div>
    </div>
</div>

And here the server side log, pay attention on timestamps.

INFO     2014-10-16 02:20:08,765 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -

INFO     2014-10-16 02:20:17,447 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -
INFO     2014-10-16 02:20:17,448 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -

INFO     2014-10-16 02:20:26,375 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -
INFO     2014-10-16 02:20:26,391 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -
INFO     2014-10-16 02:20:26,394 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -

INFO     2014-10-16 02:20:34,132 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -
INFO     2014-10-16 02:20:34,170 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -
INFO     2014-10-16 02:20:34,177 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -
INFO     2014-10-16 02:20:34,178 module.py:659] default: "POST /novaMarcacao HTTP/1.1" 200 -

Remove the following part from within the function validaNovaMarcacao and put it in DOM ready where it will be call only once:

$('#formNovaMarcacao').bootstrapValidator({
    //.....
.on('success.form.bv', function(e) {
    //......
});

As it is, each time you call the function validaNovaMarcacao , you are re-initializing the validator and attaching another success event handler; that's quite evident by the sequence of the number of calls: 1, 2, 3, 4, ...

Should be:

$(function() {
    $('#formNovaMarcacao').bootstrapValidator({
        //.....
    .on('success.form.bv', function(e) {
        //......
    });
});

UPDATE

Following the discussion below, the following are the changes you need to make:

Reduce the function to the following:

function formNovaMarcacao() {
    $('#formNovaMarcacao').bootstrapValidator({
        //.....
    });
}

Then the following:

$(function() {
    formNovaMarcacao();
    $('#formNovaMarcacao').on('success.form.bv', function(e) {
        //......
    });
});

You would do well not to use inline JS onclick=... .. it's just not good practice. Run formNovaMarcacao() immediately the dynamic form content is created.

That should do it.

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