update a div without refresh on the page, after insertion via ajax

Asked

Viewed 1,795 times

-1

I need to build a new (table-like) structure containing the information that has just been inserted into mysql via ajax without the page being updated.

To better specify, I currently have a while that creates the div’s of the database records, and by inserting a new precise record that updates this div creating a new element of the inserted object.

Follow my while structure:

<div class="panel-heading">Histórico</div>    
                <div class="panel-body panel-size">
                   <p>
                   <?php
                    while($linha2 = mysqli_fetch_assoc($detalhe2)) 
                    {
                   ?>

                <div class="row">
                    <div class="col-md-2">
                        <span class="user-time">
                            <i class="fa fa-user"></i> <?php echo utf8_encode($linha2["usuarioApelido"]) ?><br>
                            <i class="fa fa-clock-o"></i> <?php echo date("d/m/Y - H:i:s",  strtotime($linha2["cHistoricoData"])) ?><br>
                            <button type="button" id="excluiHistorico" title="<?php echo $linha2["cHistoricoId"] ?>" class="btn btn-danger btn-xs">Excluir</button>
                        </span>
                    </div>
                    <div class="col-md-10">
                        <span class="user-post">
                            <?php echo utf8_encode($linha2["cHistoricoDescricao"]) ?>
                        </span>
                    </div>
                </div>

                   <hr>  

                  <?php
                   }
                  ?>
                  </div>
                  <div class="panel-footer">

                          <!--FORMULARIO-->           

             <form role="form" class="formCad">
                        <div class="form-group">
                            <div class="col-xs-8">
                                <input type="text" class="form-control input-sm" name="cHistoricoDescricao" placeholder="Escreva aqui o Histórico...">
                                <input type="hidden" name="userId" value="<?php echo $_SESSION['IDUSER'] ?>">
                                <input type="hidden" name="clienteId" value="<?php echo $clienteId ?>">
                            </div>
                                <button class="btn btn-primary btn-sm" type="submit">Inserir</button>
                        </div>
                    </form>
                  </div>
              </div>

Histprovpub.php

<?php require_once("conexao/conexao.php"); ?>

<?php

  // Cadastro de histórico do cliente
    if (isset ($_POST["cHistoricoDescricao"]) ) {
        setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
        date_default_timezone_set('America/Sao_Paulo');
        $datahora  =date('Y-m-d H:i:s');


        $userId                      =  $_POST["userId"];
        $clienteId                   =  $_POST["clienteId"];
        $cHistoricoDescricao         =  utf8_decode ($_POST["cHistoricoDescricao"]);

        $inserir          = "INSERT INTO cliente_historico ";
        $inserir         .= "(usuarioId, clienteId, cHistoricoData, cHistoricoDescricao ) " ;
        $inserir         .= "VALUES " ;
        $inserir         .= "($userId, '$clienteId', '$datahora' , UCASE('$cHistoricoDescricao') ) " ;

        $retorno = array();

        $operacao_insercao = mysqli_query ($conecta,$inserir);

        echo json_encode($retorno);

    }

?>

jquery

<script>
            $('.formCad').submit(function(e) {
                e.preventDefault();
                var formulario = $(this);
                var retorno = inserirFormulario(formulario)

            });

            function  inserirFormulario(dados){
                $.ajax({
                    type:"POST",
                    data:dados.serialize(),
                    url:"php/HistProvPub.php",
                    async:false 
                })

            };
        </script>
  • let me get this straight, you collected the data and want to update the div?

  • while mounts div with results that already exist in the bank.. ajax inserts a new result that needs to put it in the same while scheme as a new element that has just been inserted without updating the page

  • 2
    1. Mount a string element template in javascript 2. In the Success or then of $.ajax write the function that will give the Append of this template (filled with json data (PHP)) 3. You need to convert the btn-Danger onclick event to work in the form of "delegate", e.g. $('. panel-Heading'). on('click','Bt-Danger', Function() { ... })
  • Is there any way you can help me set up this scheme? or give me a start to get a light

1 answer

3

If you use jQuery, the code can look like this:

HTML:

<div id="pai">
  <div class="filho"></div>
  <div class="filho"></div>
  <div class="filho"></div>
  <div class="filho"></div>
</div>

jQuery:

function ajax() {
    $.ajax({
      url:"ajax.php",  
      success:function(dados) {
         $("#pai").append(dados);
      }
   });
}

Browser other questions tagged

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