How to refresh a datatable and not the entire window?


I am developing a project with bootstrap, php pdo and mysql, I have a datatable that reads from mysql, I have a button that says "New Revenue", it already makes the entry but I want to refresh or update the datatable so that it loads the new data without having to update the whole page.

When you make the new entry from the button, just refresh the datatable section and show the new entry.

For now I do it by refreshing the whole page with a window.location.href after receiving the ok from the jquery that made the entry to the base of the new row.

You already load it using the response of @ Maykol-Rivas, but I stop working an action, as you will see the table has the data and in the last column you have some actions, for now there is the action of "create history"

               <tr class="odd gradeX">
                <td id="pacedula">14</td>
                <td class="center">
                <li class="glyphicon glyphicon-eye-open"></li>
                <li class="glyphicon glyphicon-edit"></li>
                <li class="glyphicon glyphicon-remove"></li>
                <li class="glyphicon icon-i-outpatient crearhistoria btn"></li>

That I call her that from the js,

   $(document).ready(function() {

   function cargar_datos(){
    url: "php/mod_listar_datos.php",
    type: "POST",
    data: {opcion:1},
    success: function(data) {
             // En caso de que se ejecute
             $('#tblPacientes > tbody').html(data);

      var $cedula = $(this).closest("tr").find("#pacedula").text();       
       url : 'php/mod_cre_his_paciente.php',
       type: "POST",
       method: "post",
       data : "cedula="+ $cedula,
       beforeSend: function(){              
success:function(v) {
         $('#labelMensajespacientes').fadeIn(250).html('No se ha enviado cedula, intentelo nuevamente').delay(10000).fadeOut(250);
         //window.location.href = "ad_docentes.php";
      }else if(v==4){  
         $('#labelMensajespacientes').fadeIn(250).html('Ya se ha creado la histora Clinica del paciente con CI'+ $cedula).delay(5000).fadeOut(250);                 
      }else if(v==3){  
         $('#labelMensajespacientes').fadeIn(250).html('Se ha creado la histora Clinica').delay(2500).fadeOut(250);    

      error: function() {

$('#labelMensajespacientes').fadeIn(250).html('Error: no se puedo realizar el ingreso').delay(2500).fadeOut(250);      

But now it does not do anything that function, so I did before but what I did now does not work.

asked by Alldesign Web 02.10.2016 в 02:42

5 answers


If you load the HTML again, the DOM elements are replaced, and the new ones have not been assigned the event. Reassign them after assigning the HTML again. Better with off / on as this avoids duplicating calls.

$(".crearhistoria").off('click');$(".crearhistoria").on('click', function() { ... };

I hope it's helpful

answered by 14.10.2016 в 08:56

As the other friend says, try to make an AJAX request to update your datatable, something like this:

        url: "ruta_de_mi_archivo_php_donde_haremos_la_consulta.php",
        type: "POST",
        data: {veruser:1},
        success: function(data) {
                 // En caso de que se ejecute
                 $('#mi_tabla > tbody').html(data);

Now, in route_of_my_file_php_where_we will_consult.php you should have something like that

     //Aqui haces tu consulta para ver todos los usuarios.
     // Pero en el while que harás, deberas retornarlo con lo valores en tr y td
     while($row = mysql_fecth_array($resulconsulta)){
           $usuarios .= '<tr>
     echo $usuarios;

In this way you will directly return the content to fill in the body of the user table, or wherever you want, in fact you can do what you want, and of course, without updating the page. :) Good luck

answered by 02.10.2016 в 14:56

They already gave you an answer that suggests you serve HTML code from the server. Another option (and more standard) is to serve the records as JSON .


Assuming you make a query with LIMIT to get the last 10 records

$json = array();
// convierte el resultset a array
// para convertirlo a JSON
for($row = $rs->fetch_assoc()) {
  $json[] = $row;
echo json_encode($json);

NOTE : You must take into account the order in the query.

In your JavaScript code, you get the records in JSON by AJAX.

$.getJSON('/get_records.php', function(records) {
  $('#tabla').empty(); // limpia la tabla -> forma "fácil"
  records.forEach(function (record, i) {
    const cell = document.querySelector('table td:nth-child(${i})');
    // obtiene la clave (columna) del JSON para obtener el valor
    let key = Object.keys(record)[0];
    cell.textContent = record[key];
answered by 02.10.2016 в 15:30

Proposal 1 : When using the DataTable plugin, also use the API that provides

When I go to: link

File: tables.js - Here you can make the following changes:

  deferLoading: 0, // Indicamos que la carga inicial se hace manual
  serverSide: true, // Indicamos que todos tipo de proceso se hace en el Backend
  ajax: {
    url: 'php/mod_listar_datos.php',
    type: 'POST',
    data: function(params) {
      // Aqui deberas analizar lo que DT envia
      // y de ser necesario modificarlo a tu antojo
      // IMPORTANTE: param.draw deber ser enviado y devuelto.
      return params;
    dataSrc: function(response) {
      // Idealmnete el servidor devolveria una respuesta JSON
      // por lo que response seria un objeto

File: patients.js - Here I recommend removing the function carga_datos - And in the places where it is called, replace it with:


More info: link

Proposal 2 : Do not use the DataTable plugin and do everything by hand.

answered by 12.10.2016 в 16:00

There is a way to handle ajax with datatable, and I think it is the best way to work with the library.


$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": "data/arrays.txt"
    } );
} );


<table id="example" class="display" cellspacing="0" width="100%">

source: link

You can also find it by paging, adding fields such as "total_paginas", "volumen_registros", "following" ...

answered by 14.10.2016 в 04:41