Insert data from multiple forms without refreshing with ajax php

Asked

Viewed 482 times

0

Good morning! I’m having problem in an application, what happens; 1 - I have this guy who gets the name of the product 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 research a product appears several below with the same letter following that I typed in the search, so far so good, I put the quantity in 1 product and give an add, a refresh page and add this product in my table and do the search again and add another, and other and other, but sometimes I research and already see face 3 products I want, only I can not register the 3 at once because my page gives a refresh, I wanted to do this with ajax, only ajax doesn’t seem to work in this method, because I tried to use the e.preventDefault() Return false and it keeps updating the page, someone can help me?

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

1 answer

0


Turns out you’re adding an element, dynamically. If you are dealing with the click of a button or sending the form before it actually gets added to the page, the function will fail.

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

  • Create/Recreate in function Observer (callback) of on the page PHP
  • Use the method on of
  • If using , you can create a Observer for the events of Submit in the element body.

Let’s go to the examples.

All examples will be commented.


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>            
            /**
             * Cria uma função de callback no elemento body
             * Toda vez que ocorrer um evento `submit` algum 
             * elemento filho, do tipo "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 amount of lines.


Returning HTML with 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 downside of this last option is that you will create several scripts. This will make the page very large.

Browser other questions tagged

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