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

Asked

Viewed 1,277 times

1

I have index.php, which has side by side an insert form and a table that reflects the database, do not need to have timeout, I just want that when I make a new record in the table, it will appear in the table next, without refreshing the page, it looks like the method so far:

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

the div:

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

for now I’m trying to do so, but returns "Undefined"

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

1 answer

1


In the form Submit you make an ajax to save and if positive adds the record in the table. The return can only be the value of the record or the html of the new line. Following 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 return the html of the new row to the table for example

<tr>
   <td>Registro 1</td>
</tr>

Browser other questions tagged

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