Insert mysql with Ajax inside the While

0

I'm trying to make a dynamic insert using ajax. as shown in the image below. I want to be able to click on send from any line and make the post referring to it

HowcanIdothis?

<scripttype="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<table style="width: 20%;">
<thead>
    <tr>
        <th style="width: 1%;" class="center">Cod.</th>
        <th style="width: 18%;" >Produtos</th>
        <th class="text-center" style="width: 8%;">Valor</th>
        <th style="width: 5%;"></th>
    </tr>
</thead>
<tbody>                 

  <?
    $cmd = "SELECT * FROM produtos where id_transfer = '1' limit 5";      
    $produtos = mysql_query($cmd)or die( mysql_error());
    $count=mysql_num_rows($produtos);
    while ($linha = mysql_fetch_array($produtos)) {


 $id_produto = $linha['id_produtos'];
 $id_transfer = $linha['id_transfer'];
 $cheva = $linha['chave'];
?>                  


        <tr class="selectable">
        <td class="center"><input type="text" id="campo1" value="<?echo $id_transfer1?>" /></td>
        <td class="important"><input type="text"   id="campo2" value="<?echo "$id_produto"?>" /></td>
        <td class="text-center"><input type="text" id="campo3" value="<?echo $chave?>" /></td>
        <td class="center">
        <input type="submit" class="btn btn-danger" onclick="inserir_registo()" /><i class="fa fa-arrow-right"></i></i></a>
        </td>
        </tr>
        
asked by anonymous 06.01.2016 / 18:42

1 answer

0

The problem is in ID replication of the fields, this can not occur.

See that inside your while you replicate the ID property of your input . Instead of doing this, put an ID per line like this:

<% while ($linha = mysql_fetch_array($produtos)) { %>

<tr data-id="<%echo idDaLinha%>">
    <td><input type="text" name="campo1" /></td>
    <td><input type="text" name="campo2" /></td>
    <td><input type="text" name="campo3" /></td>
    <td><input type="button" class="botaoEnviar" data-id="<%echo idDaLinha%>">Enviar</button>
</tr>

<% } %>

And in your jQuery:

$('.botaoEnviar').click(function() {
    var id = $(this).attr('data-id');
    var $tr = $('tr[data-id='+ id +']');

    var dadosAjax = 
    {
        campo1: $tr.find('input[name=campo1]').val(),
        campo2: $tr.find('input[name=campo2]').val(),
        campo3: $tr.find('input[name=campo3]').val()
    };

    // sua chamada ajax
});
    
07.01.2016 / 12:38