Update table html after registering user using ajax

1

Hello, I have a following js code to register a user.

$(function() {

    $('#cadastrar_usuario').submit(function(event) {
        event.preventDefault();
        var formDados = new FormData($(this)[0]);

        $.ajax({
            url: 'func_cadastrar_usuario.php',
            type: 'POST',
            data: formDados,
            cache: false,
            contentType: false,
            processData: false,
            success: function(data) {
                $('#resultado').html(data);

            },

            complete: function(data) {
                $('#cadastrar_usuario').each(function() {
                    this.reset();
                });

            },

            dataType: 'html'
        });
        return false;
    });
});

And I have an html table where I list the users registered in the database with PHP.

I'd like to know how to get the user table updated after the user's registration, without refresh or reload, as I do at the time of registration. Type, do not complete the function to register, I update the table.

NOTE: In the file func_address_user.php, I only receive the data from the registration form, there I insert and register in the database. If you can do it there, too.

Thank you very much for any help.

I will be leaving here my files Usuarios.php, where you have a div with the database user list tables, and a div with a user registration form.

<div id="listar">
    <table id="exibir_dados" width="660" height="115">
        <tr id="titulos">
        <td width="30" height="32">ID</td>
        <td width="330">NOME</td>
        <td width="166">E-MAIL</td>
        <td width="70">SEXO</td>
        <td width="5">LOGIN</td>
        <td width="86">AÇÔES</td>
        </tr>

        <?php
            include("conexao.php");
            $sql = mysql_query("SELECT * FROM usuarios ORDER BY id ASC");

            $c = 2;
            $cores = array("#FFFFFF","#EAF4FF");


            while($coluna = mysql_fetch_array($sql)){
                $id    = $coluna["id"];
                $nome  = $coluna["nome"];
                $email = $coluna["email"];
                $sexo  = $coluna["sexo"]; 
                $login = $coluna["login"];

                $index = $c % 2;
                $c++;
                $cor = $cores[$index];

         ?>
              <tr id="lista" bgcolor="<?=$cor?>">
                <td width="30" height="32"><?php echo $id;?></td>
                <td width="165"><?php echo $nome;?></td>
                <td width="166"><?php echo $email;?></td>
                <td width="87"><?php echo $sexo;?></td>
                <td width="134"><?php echo $login;?></td>
                <td width="86"><a id="alterar" href="">Alterar</a><a href="" id="<?php echo $id;?>" class="excluir">Excluir</a></td>
              </tr>
          <?php
          }
          ?>
    </table>      
    </div>


    <div id="usuario">
        <h1>CADASTRO DE USUÁRIOS</h1>
        <form id="cadastrar_usuario" action="" method="post" class="form_group">
            <table id="cadastrar">
                    <p id="resultado" hidden=""></p>
                  <tr> 
                    <td id="titulo">Nome:</td>
                    <td><input type="text" class="txt" name="nome" id="nome" maxlength="30" placeholder="Insira um Nome" /></td>
                  </tr>
                  <tr>
                    <td id="titulo">E-mail:</td>
                    <td><input type="email" class="txt" name="email" id="email" maxlength="30" placeholder="Insira um E-mail"/></td>
                  </tr>
                  <tr>
                    <td id="titulo">Sexo:</td>
                    <td><input type="radio" name="sexo" id="masc" value="masculino" checked/> <label for="masc">Masculino</label>
                        <input type="radio" name="sexo" id="fem" value="feminino"/> <label for="fem">Feminino</label>
                    </td>
                  </tr>
                  <tr>
                    <td id="titulo">Login:</td>
                    <td><input type="text" class="txt" name="login" id="login" maxlength="15" placeholder="Insira um login" /></td>
                  </tr>
                  <tr>
                    <td id="titulo">Senha:</td> 
                    <td><input type="password" class="txt" name="senha" id="senha" maxlength="8" placeholder="8 dígitos" /></td>
                  </tr>
                  <tr>
                    <td>&nbsp;</td>
                    <td><button type="submit">Cadastrar</button></td>
                  </tr>
             </table>
         </form>
    </div>

File func_over_user.php, where I register the users

<?php
include("conexao.php");


@$nome  = $_POST["nome"]; 
@$email = $_POST["email"];
@$sexo  = $_POST["sexo"];
@$login = $_POST["login"];
@$senha = md5($_POST["senha"]);

if(empty($nome)){

    echo"<script>alert('Campo Nome está vazio!!!');</script>";

}elseif(empty($email)){

    echo"<script>alert('Campo E-mail está vazio!!!');</script>";

}elseif(empty($login)){

    echo"<script>alert('Insira um Login!!!');</script>";

}elseif($senha == 'd41d8cd98f00b204e9800998ecf8427e'){

    echo"<script>alert('Insira uma Senha!!!');</script>";

}else{

    $consuta = mysql_num_rows(mysql_query("SELECT * FROM usuarios WHERE login = '$login'"));

    if($consuta == 1){

        echo"<script>alert('Login já cadastrado!!!'); </script>";

    }else{

        mysql_query("INSERT INTO usuarios (nome, email, sexo, login, senha) VALUES ('". $nome ."','". $email ."', '". $sexo ."', '". $login ."', '". $senha ."')");
        echo"<script>alert('Usuário Cadastrado com Sucesso!!!');</script>";
    }
}

}
?>
    
asked by anonymous 15.07.2016 / 21:48

1 answer

1

I suggest you create a template on the server side. In the background is a piece that you can copy, insert the new data and put it in the table.

So on the server it generates this when the page generated:

<template>
    <tr>
        <td data-name="id"></td>
        <td data-name="nome"></td>
        <td data-name="email"></td>
        <td data-name="sexo"></td>
        <td data-name="login"></td>
        <td width="86"><a id="alterar" href="">Alterar</a><a href="" id="" class="excluir">Excluir</a></td>
    </tr>
</template>

Then in JavaScript you will search for this tr clone it and enter the new data:

$('#cadastrar_usuario').submit(function(event) {
    event.preventDefault();
    var form = this;
    var formDados = new FormData(form);

    $.ajax({
        url: 'func_cadastrar_usuario.php',
        type: 'POST',
        data: formDados,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) {
            $('#resultado').html(data);
            var tr = document.querySelector('template').content.querySelector("tr");
            var clone = document.importNode(tr, true);
            $(clone).find('td').each(function() {
                var type = this.dataset.type;
                if (type) {
                    this.innerTHML = form.querySelector('[name="' + type + '"]').value;
                } else {
                    // caso da ultima td
                    $(this).find('a').last().attr('id', form.querySelector('[name="id"]').value);
                }
            });
            $('#exibir_dados').append(clone);
        },

Note:

  • In your code there are several errors, it is possible that my solution does not work at first, but it shows you the way forward.

  • I do not recommend using CSS in attributes, inline, as <td width="30" . This makes code maintenance very difficult.

  • IDs must be unique. No page element can have the same ID as another. This is the fundamental difference between class and id .

15.07.2016 / 23:49