How to update a table through AJAX?

Asked

Viewed 30 times

-1

Hello. I would like to, when clicking on "register" in the div "register-customers" be updated the client table in the div "Md-clients", but I do not know how to make the table update without updating all html.

DIV client register:

<div class="modal" tabindex="-1" role="dialog" id="cadastro-clientes">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5>Cadastro de clientes</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form method="POST" id="cad-form" name="cad-form" action="cadastro.php">
              <div class="form-group cad-container">
                <label>Qual o nome completo?</label>
                <input class="form-control" name="nome" placeholder="Nome e sobrenome">
                <label>E a data de nascimento?</label>
                <input inputmode="numeric" name="data_nasc" class="form-control um" id="cad-dat-nasc" placeholder="Ex: 01/01/2020">
                <label>Qual o telefone? </label>
                <input inputmode="numeric" name="telefone" class="form-control um" id="cad-tel"placeholder="Ex: (99) 9 9999-9999">
                <label>Onde mora? </label>
                <input class="form-control" name="endereco" placeholder="Rua, numero, bairro e cidade">
                <label>Qual o CPF?</label>
                <input inputmode="numeric" name="cpf" class="form-control um" id="cad-cpf" placeholder="Ex: 999.999.999-99">
                <label>E o RG?</label>
                <input inputmode="numeric" name="rg" class="form-control um" id="cad-rg"placeholder="Ex: 99.999999-9">
              </div>
              <!--o cad-btn deve estar dentro do formulario-->
              <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" id="volta-btn">Voltar</button>
                <button type="submit" class="btn btn-outline-primary" id="cad-btn">Cadastrar</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

div Md-clients:

  <div class="modal" tabindex="-1" role="dialog" id="md-clientes">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header clientes-container">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
          <h5>Pesquisar clientes</h5>
          <div class="input-group mb-3">
            <div class="input-group-prepend">
              <span class="input-group-text"><i class="fas fa-search"></i></span>
            </div>
            <input type="text" class="form-control center" placeholder="Informe o nome">
          </div>
        </div>
        <div class="modal-body">
          <!--tabela clientes-->
          <div class="modal-body">
            <!--tabela clientes-->
            <div data-spy"scroll" data-target="modal-body" data-offset="0" class="scroll-height">
              <div class="bd-example">
                <div class="table-responsive-lg">
                  <table class="table table-striped" id="tabela-clientes">
                    <thead>
                      <tr>
                        <th scope="col">ID</th>
                        <th scope="col">Nome</th>
                        <th scope="col">Telefone</th>
                        <th scope="col">CPF</th>
                        <th scope="col">RG</th>
                        <th scope="col">Endereço</th>
                      </tr>
                    </thead>
                    <tbody>
                      <!-- laco de repeticao de clientes -->
                      <?php
                        include("cadastro.php");
                        $grupo = exibirClientes(); ?>

                        <?php
                        foreach($grupo as $dados){
                        ?>
                          <tr>
                              <td><?=$dados["nome"] ?> </td>
                              <td><?=$dados["dataNascimento"] ?> </td>
                              <td><?=$dados["telefone"] ?> </td>
                              <td><?=$dados["cpf"] ?> </td>
                              <td><?=$dados["rg"] ?> </td>
                              <td><?=$dados["endereco"] ?> </td>
                            </tr>
                        <?php
                        }
                        ?>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-primary" id="md-cadastro">Cadastro</button>
            <button type="button" class="btn btn-outline-danger">Deletar</button>
          </div>
        </div>
      </div>
    </div>

javascript (ajax):

$('form[name="cad-form"]').submit(function(){
  var dados = $(this).serialize();
    $.ajax({
      url: 'cadastro.php',
      type: 'post',
      data: dados,
      success:function(data){
        if (data == "sucesso") {
          alert("Cliente cadastrado com sucesso! :)");
          }
          /*caso nao retorne "sucesso", mas realiza o cadastro, retorna oq houve
            de errado*/
          else {
            alert(data);
          }

        }
    })
    // "trava" o submit
  return false;
})

Thank you from now on and have a great day!

  • Let me get this straight, you want when registering a new item to automatically appear in the div without updating?

  • That’s right! In the current case, the item only appears in the table when updating html

1 answer

0

You should use the jquery’s "append()" function to add the items that come from your form to the html div

let nome = "";
let dataNascimento = "";
let telefone = "";
let cpf = "";
let rg = "";
let endereco = "";

let tr = `<tr>
            <td>${nome}</td>
            <td>${dataNascimento}</td>
            <td>${telefone}</td>
            <td>${cpf}</td>
            <td>${rg}</td>
            <td>${endereco}</td>
          </tr>`;

$("body #tabela-clientes tbody").append(tr)

in the variables, you put the data that comes from the form, and as soon as you finish the request the items will be added (append) to the end of your DIV. Thus...

$('form[name="cad-form"]').submit(function(){
  var dados = $(this).serialize();
    $.ajax({
      url: 'cadastro.php',
      type: 'post',
      data: dados,
      success:function(data){
        if (data == "sucesso") {
        
            let nome = "nomeQueVemDoForm";
            let dataNascimento = "datadeNascQueVemDoForm";
            let telefone = "telefoneQueVemDoForm";
            let cpf = "cpfQueVemDoForm";
            let rg = "rgQueVemDoForm";
            let endereco = "enderecoQueVemDoForm";

            let tr = `<tr>
                        <td>${nome}</td>
                        <td>${dataNascimento}</td>
                        <td>${telefone}</td>
                        <td>${cpf}</td>
                        <td>${rg}</td>
                        <td>${endereco}</td>
                      </tr>`;

            $("body #tabela-clientes tbody").append(tr)

        }
          /*caso nao retorne "sucesso", mas realiza o cadastro, retorna oq houve
            de errado*/
          else {
            alert(data);
          }

        }
    })
    // "trava" o submit
  return false;
})

Browser other questions tagged

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