Update after typing without refresh

0

I have a list of names that come from the database and need to update these names when necessary. I bring everyone already inside the form and update with a Javascript.

With a registry works perfectly. The problem is when I bring more than one bank name, so it only works on the first form.

<?php
$consulta = mysql_query("
SELECT * FROM categoria limit 2");
while ($dados = mysql_fetch_array($consulta)) {
?>
<form method="POST" action="" id="ajax_form">
    <div class="row">
        <div class="col-md-6 form-group">
            <input type="text" id="id_categoria" name="id" class="form-control" value="<?echo$dados['id_categoria']?>" readonly>
            <input type="text" id="nome" name="nome" class="form-control" maxlength="100" placeholder="Seguimento" value="<?echo$dados['nome']?>" required autofocus>
            <button class="btn btn-primary" type="submit">Atualiza</button>
        </div>
    </div>
</form> 
<?}?>

JS

<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#ajax_form').submit(function(){
    var data = { 
       id_categoria: $('#id_categoria').val(),
       nome: $('#nome').val()
      };
    $(this).text("Atualizando"); // Aqui voce muda o texto do botao caso queira
    $.ajax({
        type: "POST",
        url: "seguimento_lista_sql_update.php",
        data: data,
        cache: true
    })
});
}); 
</script>   
    
asked by anonymous 23.03.2016 / 19:53

1 answer

0

Try this simpler way, I made some updates on the form so the button has an id (the same as the category) and the text field has an id too (s + category_id), I changed the submit to button and added a class I also removed the field id_category because it was not necessary, if you want to display it, just adapt it in the template:

Form with changes:

<form method="POST">
    <div class="row">
        <div class="col-md-6 form-group">
            <input type="text" class="form-control" id="s<?=@$dados['id_categoria']?>" maxlength="100" placeholder="Seguimento" value="<?=@$dados['nome']?>" required autofocus>
            <button id="<?=@$dados['id_categoria']?>" class="btn btn-primary atualiza" type="button">Atualiza</button>
        </div>
    </div>
</form>

JQuery:

<script type="text/javascript">
    jQuery(document).ready(function(){
        $('button.atualiza').click(function() {
            botao = $(this);
            botao.text("Atualizando");
            $.ajax({
                type: "POST",
                url: "seguimento_lista_sql_update.php",
                data: { id_categoria: botao.attr('id'), nome: $('input#s'+botao.attr('id')).val() },
                cache: true
            }).done(function(data) {
                botao.text("Atualiza");
            });
        });
    }); 
</script>  

I hope it helps, hugs

    
23.03.2016 / 22:10