Update table html after registering user using ajax

Asked

Viewed 715 times

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 users registered in the database with PHP.

I would like to know how to make that after the user registration, this table of users is updated without refresh or Reload, as I do when registering. Type, at the completion of the registration function, I update the table.

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

I thank you from my heart for any help.

I’ll be leaving my user.php files here, where you have a div with the database’s 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_cadastrar_usuario.php, where I register 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>";
    }
}

}
?>
  • I didn’t understand if you want to update in HTML or in the database? If it is in HTML you can put an example table?

  • i have a page with 1 html table that lists the database data, and a form that register a user. In the registration part I use the function with ajax I posted where I register the user without doing Reload. What I want is that when I register a user, the html table that lists already registered users, is updated with the new registered user.

  • and I would like to update the table in the same function as I register the user, type in the part of Success or complete function.

  • What information are you passing on data here $('#resultado').html(data);?

  • is just a field Hidden that I use to make a check,it doesn’t have much importance, don’t worry.

  • My idea is for you to pass on that date the information if Insert was successful. And if so, you can do append in the table with the form data before you do .reset

  • perfect, could make an example? if you need some code part of some file...

  • I need a part of your code that I mentioned above..., an example of what this table looks like and the form fields.

Show 3 more comments

1 answer

1

I suggest you create a template on the server side. At the bottom is a piece you can copy, insert the new data and place in the table.

So on the server generates this when the generated page:

<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 get 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 to follow.

  • advise against using CSS in attributes, inline, such as <td width="30". This makes it very difficult to maintain the code.

  • Ids must be unique. No element on the page can have the same ID as another. That’s the fundamental difference between class and id.

  • 1

    Thank you so much for the advice and attention you have given me. It really didn’t work at first but I will "poke around" a little bit here.

  • @Joelsonsantos had forgotten to $('#exibir_dados').append(clone);, joined now. Yes, do it. If you want you can put here the error that gives you in the console.

  • 1

    @Joelsonsantos after testing your code, following the answer guidelines, it is advisable to replace the functions mysql_, for mysqli_. http://php.net/manual/en/book.mysqli.php

Browser other questions tagged

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