Ajax function running multiple times even being called only once

Asked

Viewed 216 times

-1

Hello, I’m having the following problem: I have a modal that should make the inclusion of a form in the database. The Submit button calls a Javascript/Ajax function, which in turn calls a php page with the query. So far so good, the data is entered successfully. But the second time I run the function, it runs twice. The third time, three times. And so on and so forth. I tried calling the function through the form action, through the Submit button and through the onclick function and got the same result in all ways. What may be causing this problem?

Follow the modal code

<!-- Modal Adicionar Item-->
<div class="modal fade" id="modalItemAdd" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form enctype="multipart/form-data" id="addItemComanda" name="addItemComanda">
                <div class="modal-header">
                    <h4 class="modal-title">Adicionar item</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Código</label>
                        <input type="text" class="form-control" name="cod_item" id="cod_item" required>
                    </div>
                    <div class="form-group" id="form_lista_prod">                          
                        <label>Selecione um produto</label>  
                        <input onclick="listarProdutos();" type="text" name="select_produtos" id="select_produtos" class="form-control" placeholder="Digite o nome do produto" />  
                        <div id="listaProdutos"></div>  
                    </div> 

                    <input type="hidden" name="id_comanda" value="12">

                    <div class="form-group">
                        <label>Quantidade</label>
                        <input type="text" class="form-control" name="qtde_item" id="qtde_item" value="1" required>
                    </div>
                </div>                
                <div class="modal-footer">
                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancelar">
                    <input type="submit" class="btn btn-primary" value="Adicionar" onclick="addItemCom()">
                </div>
            </form>
        </div>
        </div>
    </div>
</div>

Follow the function code:

function addItemCom() {
$('form').submit(function () {
    var dados = $(this).serialize();
    $.ajax({
        url: 'additemcomanda.php',
        method: 'post',
        dataType: 'html',
        data: dados,
        success: function (data) {
            alert("Teste dessa bagaça");
            $('#resultado').empty().html(data);
        }
    });
    return false;
});

$('form').trigger('submit');
$.ajax().empty();

}

And follow the php code with the query:

session_start(); include_once("config.php"); $idcom = $_POST['id_comanda']; $cod_item = $_POST['cod_item']; $nom_item = $_POST['select_produtos']; $qtd_item = $_POST['qtde_item']; if(!empty($idcom)){ $result_usuario = "INSERT INTO PROD_COMANDA (COD_COMANDA, COD_PROD, NOME_PROD, QUANTIDADE, VL_UNIT, VL_TOTAL) VALUES ('$idcom', '$cod_item', '$nom_item', '$qtd_item', (SELECT PRECO FROM CAD_PROD WHERE CODIGO='$cod_item'), (VL_UNIT*QUANTIDADE))"; $resultado_usuario = mysqli_query($mysqli, $result_usuario);
echo $result_usuario;
}else{
echo "Falha ao adicionar o item!"; }

Thank you in advance

1 answer

1

Putting onclick="addItemCom()" on the Submit button, each time the function is called will create in memory an instance of the event $('form').submit, so you’re multiplying the event trigger.

It is not necessary a function for this, just the Event Handler with the id of the form in question:

$('#addItemComanda').submit(function (e) {
    e.preventDefault();
    var dados = $(this).serialize();
    $.ajax({
        url: 'additemcomanda.php',
        method: 'post',
        dataType: 'html',
        data: dados,
        success: function (data) {
            alert("Teste dessa bagaça");
            $('#resultado').empty().html(data);
        }
    });
});

See that I added the e.preventDefault(); to avoid page reloading (no need to return false).

Remove the attribute onclick="addItemCom()" from the Ubmit button.

  • Thanks for the reply, but this way ended up not working, apparently did not get to perform the function. I also worry if by chance other Forms I come to have on this page may not end up calling the function this way?

  • Place the form id on the event selector: $("#addItemComanda").submit

  • I changed the answer with the correct selector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.