Send data from a dynamic table via ajax

Asked

Viewed 1,028 times

2

I have a dynamic table, where I can add or remove a row, when I add a new row I can send that writing by the form... But not how much I try to send via ajax , just sends the first line. How right it would be to send all the new lines?

Html code

<table id="table" class="table table-striped table-bordered table-hover" data-url="data1.json" data-height="299" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" class="table table-striped table-condensed">
    <thead>
        <tr class="text-center">
            <th data-field="categoria" data-radio="true">Nº do Item</th>
            <th data-field="categoria" data-radio="true">Quantidade</th>
            <th data-field="categoria" data-radio="true">Preço unitário</th>
            <th data-field="categoria" data-radio="true">Regra destribuição</th>
            <th data-field="categoria" data-radio="true">Total</th>
            <th>-</th>
        </tr>
    </thead>
    <tbody>
        <tr class="linhas odd gradeX">
            <td><input type="text"  name="item_cod[]" id="item_cod" /></td>
            <td><input type="text"  name="quantidade[]" id="quantidade"/></td>
            <td><input type="text"  name="preco_und[]" id="preco_und" /></td>
            <td><input type="text"  name="regra_dest[]" id="regra_dest" /></td>
            <td><input type="text"  name="total[]" id="total" /></td>
            <td>
                <a href="#" class="btn btn-danger evento-btn-excluir tooltip-info excluir removerCampo"  data-toggle="tooltip" data-placement="top" title="Excluir" value="">
                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>
            </td>
        </tr>
        <tr>
            <td colspan="6">
                <input type="text" name="qtdLinhas" id="qtdLinhas" value="1" style="width:40px;" />
                <a href="#" class="adicionarCampo"  data-toggle="tooltip" data-placement="top" title="Adicionar linha">                                               
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                </a>
            </td>
        </tr>
    </tbody>
</table>                    
<button  id="enviar" class="btn btn-success text-right" type="submit">
    <i class="fa fa-fw fa-save"></i> Salvar
</button>

ADD AND REMOVE LINES

$(function () {
 function removeCampo() {
 $("removerCampo").off("click");
 $(".removerCampo").on("click", function (){
  if($("tr.linhas").length > 1){
  $(this).parent().parent().remove();
  }   }); }  

$(".adicionarCampo").on("click", function (){
 var qtdLinhas = $("#qtdLinhas").val();
  for ( var i = 0 ; i < qtdLinhas ; i++ ){ 
   novoCampo = $("tr.linhas:first").clone(); 
   novoCampo.find("input").val(""); 
   novoCampo.insertAfter("tr.linhas:last"); 
   removeCampo(); } }); });

AJAX

$(document).ready(function(){    

    $('#enviar').click(function(){

        var item_cod = (document.getElementById('item_cod').value);
        var quantidade = (document.getElementById('quantidade').value);
        var preco_und = (document.getElementById('preco_und').value);
        var regra_dest = (document.getElementById('regra_dest').value);
        var total = (document.getElementById('total').value);
        var fornecedor =  (document.getElementById('fornecedor').value); 
        var data_lancamento = (document.getElementById('data_lancamento').value); 


        $.ajax({       
            type:"POST",            
            url:'./produtos/cadastrar-produto',                   
            data:{
                item_cod:item_cod,
                quantidade:quantidade,              
                preco_und:preco_und,
                regra_dest:regra_dest,
                total:total,
                fornecedor:fornecedor,
                data_lancamento:data_lancamento,                      
                _token: $('input[name="_token"]').val()
            },  
        });           
    }); 
});
  • It seems to me that you are sending arrays and in ajax you are treating as string. In Ajax you would have to create arrays as well.

  • I had already done some research on this, but had not found the correct form

  • Why arrays in inputs? I think there is no such need

1 answer

1


Well, I initially pulled some values from the code javascript that had not in the html, after that the code practically worked, I made adjustments not to spend variables etc:

HTML: (I made small adjustments in wrong parameters)

<table id="table" class="table table-striped table-bordered table-hover table-condensed" data-url="data1.json" data-height="299" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1">
    <thead>
        <tr class="text-center">
            <th data-field="categoria" data-radio="true">Nº do Item</th>
            <th data-field="categoria" data-radio="true">Quantidade</th>
            <th data-field="categoria" data-radio="true">Preço unitário</th>
            <th data-field="categoria" data-radio="true">Regra destribuição</th>
            <th data-field="categoria" data-radio="true">Total</th>
            <th>-</th>
        </tr>
    </thead>
    <tbody>
        <tr class="linhas odd gradeX">
            <td><input type="text"  name="item_cod[]" id="item_cod" /></td>
            <td><input type="text"  name="quantidade[]" id="quantidade"/></td>
            <td><input type="text"  name="preco_und[]" id="preco_und" /></td>
            <td><input type="text"  name="regra_dest[]" id="regra_dest" /></td>
            <td><input type="text"  name="total[]" id="total" /></td>
            <td>
                <a href="#" class="btn btn-danger evento-btn-excluir tooltip-info excluir removerCampo"  data-toggle="tooltip" data-placement="top" title="Excluir">
                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                </a>
            </td>
        </tr>

        <tr>
            <td colspan="6">
                <input type="text" name="qtdLinhas" id="qtdLinhas" value="1" style="width:40px;" />
                <a href="#" class="adicionarCampo"  data-toggle="tooltip" data-placement="top" title="Adicionar linha">                                               
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                </a>
            </td>
        </tr>
    </tbody>
</table>                    
<button  id="enviar" class="btn btn-success text-right" type="submit">
    <i class="fa fa-fw fa-save"></i> Salvar
</button> 

Javascript 01: (Using the $.ajax)

$(document).ready(function(){    

    $("#enviar").click(function(){

        $.ajax({       
            type:"POST",            
            url:'recebe.php',                   
            data:{
                item_cod:       $('#item_cod').val(),
                quantidade:     $('#quantidade').val(),              
                preco_und:      $('#preco_und').val(),
                regra_dest:     $('#regra_dest').val(),
                total:          $('#total').val()
            },
            success: function(retorno) {
                alert(retorno);
            }
        });  
    });           
});

Javascript 02: (using $.post)

$(document).ready(function(){    

    $("#enviar").click(function(){ 
        $.post('recebe.php', 
            'item_cod='    + $('#item_cod').val()  +
            '&quantidade=' + $('#quantidade').val() +
            '&preco_und='  + $('#preco_und').val()  +
            '&regra_dest=' + $('#regra_dest').val() +
            '&total='      + $('#total').val(),
        function(retorno){
            alert(retorno);
        });
    });           
});

PHP: (returns all values if successful, or 'fail' if failed)

<?php

if(isset($_POST['item_cod']) && isset($_POST['quantidade']) && isset($_POST['preco_und']) &&
   isset($_POST['regra_dest']) && isset($_POST['total'])) {

    echo $_POST['item_cod']." - ".$_POST['quantidade']." - ".$_POST['preco_und']." - ".
        $_POST['regra_dest']." - ".$_POST['total'];
} else {

    echo 'fail';
}

?>
  • My old man thank you, saved me a lot, I was already 3 days stuck in this looking for the way to do! brigadeo!

  • If the answer solved the problem click on the right sign () left it so other members can see that the question had a valid answer.

  • had to use serialize to pass the array...

Browser other questions tagged

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