I want to use ajax to simply update a table that reflects the database, without refreshing the page

1

I have the index.php, which has side by side an insert form and a table that reflects the bank, does not need to have timeout, just want it when I make a new record in the table, it will appear in the table next, without doing refresh in the page, it looks like this the method until now:

 function atualizarTabela(){
                xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", "select.php", false);
                xmlhttp.send(null);
                document.getElementById("tabela").innerHTML=xmlhttp.reponseText;                        
            }

a div:

<div id="tabela"></div>

For now I'm trying to do this, but returns "undefined"

This page select.php so far only has an echo saying that it worked, for testing, but it will do select in the database and echo echo the results of the table.

    
asked by anonymous 14.07.2016 / 22:05

1 answer

1

In the submit form you make an ajax to save and if positive add the record to the table. The return can be just the registry value or the html of the new line. Here's an example:

$("#form").submit(function(e) {
  e.preventDefault();
  var $form = $(this);
  $.ajax({
    url: "select.php",
    type: "GET",
    data: $form.serialize(),
  })
  .done(function(novoRegistro) {
    $("#tabela table").append(novoRegistro);
  })
  .fail(function() {
    console.log("erro ao salvar");
  });
});

And in your div you would have something like:

<div id="tabela">
  <table></table>
</div>

And your select.php would return the html of the new row for the table eg

<tr>
   <td>Registro 1</td>
</tr>
    
15.07.2016 / 04:35