Insert data from multiple forms without refresh with ajax php

0

Good morning! I'm having trouble with an application, which happens; 1 - I have this guy who gets the product name and shows my list:

var req;

function buscarProd(valor) {

if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
}

var url = "system/pedidos/data.php?valor=" + valor;

req.open("Get", url, true);

req.onreadystatechange = function () {

    if (req.readyState == 1) {
        document.getElementById('resultado').innerHTML = '<div class="buscprod">Buscando produto...</div>';
    }

    if (req.readyState == 4 && req.status == 200) {

        var resposta = req.responseText;

        document.getElementById('resultado').innerHTML = resposta;
    }
}
req.send(null);

}

along with this:

$Valor = filter_input(INPUT_GET, 'valor', FILTER_DEFAULT);
if (empty($Valor)):
 exit;
endif;
$Like = "%{$Valor}%";
$Read = new Read;
$Read->ExeRead("produto", "WHERE descricao LIKE :val ORDER BY descricao ASC", "val={$Like}");

foreach ($Read->getResult() as $Produtos):
?>
<form name="FormProd" id="FormProd" method="post" action="#">
    <table style="width: 100%; text-align: left;">


        <tr><td><input type="hidden" value="<?php echo $Produtos['codigo']; ?>" name="codpro"/></td></tr>

        <tr> 
            <td colspan="3">

                <?php echo $Produtos['descricao']; ?>

            <td>
        </tr>
        <tr>  
            <td colspan="1">
                <input style="padding-left: 4px; padding-right: 4px;" name="qntpro" type="number" placeholder="Qnt" />
            <td> 
            <td style="display: none"><input name="nome_usu" type="hidden" value="<?php echo $userlogin['nome_usu']; ?>"/></td>
            <td style="width: 60px;">
                <input type="submit" name="btnForm" class="circleCar right icon-add" value="Add"/>
                <!--<div class="icon-add"></div>-->
            <td>

    </table>
</form>   

<?php
  endforeach;
?>

The problem is that when I search for a product appears several in below with the same letter tracking I typed in the search, so far so good, I put the quantity in 1 product and give an add, the page of a refresh and I add this product in my table and I do the research again and add another, and another and another, but sometimes I search and I already see the 3 products I want, but I can not register the 3 at a time because my page of one refresh, I wanted to do this with ajax, so ajax does not seem to work in this method, since I already tried to use e.preventDefault() return false and it keeps updating the page, can anyone help me?

Remembering, I'm giving the foreach on a form, ie each product is in 1 form with an input for its quantity.

    
asked by anonymous 06.03.2018 / 07:37

1 answer

0

It turns out that you are adding an element dynamically. If you are dealing with the button click or submitting the form before it actually is added to the page, the function will fail.

There are three ways you can work with functions for dynamic elements:

  • Create / Recreate function in the Observer (callback) / questions / tagged / xmlhttprequest "class=" post-tag "title = tag 'xmlhttprequest' "> xmlhttprequest on PHP
  • Use method on of
  • If you are using , you can create a Observer for the submit events in the body element.

Let's go to the examples.

All examples will be commented out.

Example with Vanilla

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
    </head>

    <body>
        <script>
            /**
             * Função anônima para requisições
             *
             * @param args Object. Ex: {
             *    url:        String,
             *    method:     String,
             *    postfields: FormData|String|Null,
             *    callback:   Function
             *}
             */
            const request = function( args ) {
                const { url, method, postfields, callback } = args

                const xhr = new XMLHttpRequest();
                xhr.addEventListener("load", callback);
                xhr.open(method, url, true);
                xhr.send(postfields);
            }

            /**
             * Cria uma função de callback
             * Toda vez que ocorrer um evento 'submit' no "body"
             * ou em algum elemento filho, essa função será
             * engatilhada.
             */
            document.querySelector("body").addEventListener( "submit", event => {
                event.preventDefault();

                request({
                    url: 'https://stackoverflow.dev/insert',
                    method: 'POST',
                    postfields: new FormData(event.target),
                    callback: result => alert( result.target.response )
                })
            })

            /**
             * Utiliza a função de request para carregar a página
             * do formulário
             */
            request({
                url: 'https://stackoverflow.dev/load-form',
                method: 'GET',
                postfields: null,
                callback: function(result) {
                    document.querySelector("body").insertAdjacentHTML('beforeend', result.target.response)
                }
            })
        </script>
    </body>
</html>

Example with jQuery

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
    </head>

    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script>/***Criaumafunçãodecallbacknoelementobody*Todavezqueocorrerumevento'submit'algum*elementofilho,dotipo"form", essa função será
             * engatilhada.
             */
            $("body").on("submit", "form", function(e) {
                e.preventDefault();

                $.post("https://stackoverflow.dev/insert", $(this).serialize(), function(result) {
                    alert( result )
                })
            })

            /**
             * Utiliza a função de request para carregar a página
             * do formulário
             */
            $("body").load("https://stackoverflow.dev/load-form");
        </script>
    </body>
</html>
  

If you already use JQuery in your project, this example is good considering the number of lines.

Returning the HTML with the Javascript function

<?php
$Valor = filter_input(INPUT_GET, 'valor', FILTER_DEFAULT);
if (empty($Valor)):
 exit;

endif;
$Like = "%{$Valor}%";
$Read = new Read;
$Read->ExeRead("produto", "WHERE descricao LIKE :val ORDER BY descricao ASC", "val={$Like}");

foreach ($Read->getResult() as $Produtos):

$id = uniqid();
?>
<form name="FormProd" id="<?php echo "FormProd{$id}" ?>" method="post" action="#">
    <table style="width: 100%; text-align: left;">


        <tr><td><input type="hidden" value="<?php echo $Produtos['codigo']; ?>" name="codpro"/></td></tr>

        <tr> 
            <td colspan="3">

                <?php echo $Produtos['descricao']; ?>

            <td>
        </tr>
        <tr>  
            <td colspan="1">
                <input style="padding-left: 4px; padding-right: 4px;" name="qntpro" type="number" placeholder="Qnt" />
            <td> 
            <td style="display: none"><input name="nome_usu" type="hidden" value="<?php echo $userlogin['nome_usu']; ?>"/></td>
            <td style="width: 60px;">
                <input type="submit" name="btnForm" class="circleCar right icon-add" value="Add"/>
                <!--<div class="icon-add"></div>-->
            <td>

    </table>
</form>

<script>
    /* Cria uma função para eventos de submit do formulário */
    $("#<?php echo "FormProd{$id}" ?>").submit(function(e) {
        e.preventDefault();

        $.post("https://stackoverflow.dev/insert", $(this).serialize(), function(result) {
            alert( result )
        })
    })
</script>
<?php endforeach; ?>
  

The disadvantage of this latter option is that you will create multiple scripts . This will make the page very large.

    
06.03.2018 / 09:19