How do I refresh my data without updating the full page?

advertisements

I'm using PHP, MySQL, DataTables and modal Bootstrap 3 to code an AJAX form, I've achieved loading data from my MySQL database but I can't see new data without refreshing the entire page. This is my code:

color.php

<?php
    session_start();
    require_once '../../class/query_color.php';
    $objColor = new Color;
?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <link rel="icon" type="image/png" href="../ico/icono.ico">
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Administración de colores</title>

        <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../css/dataTables.bootstrap.css">
        <link rel="stylesheet" type="text/css" href="../css/dataTables.colVis.css">
        <link rel="stylesheet" type="text/css" href="../css/bootstrap-select.min.css">
        <script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
        <script type="text/javascript" src="../js/bootstrap.min.js"></script>
        <script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" src="../js/dataTables.bootstrap.js"></script>
        <script type="text/javascript" src="../js/dataTablesLanguage.js"></script>
        <script type="text/javascript" src="../js/dataTables.colVis.js"></script>
        <script type="text/javascript" src="../js/bootstrap-select.min.js"></script>
        <script type="text/javascript" src="../js/dataTables.fnReloadAjax.js"></script>
    </head>
    <body>
        <div class="container" id="container">
        <?php
            $consulta = $objColor->select_color();
            include('modal_add_color.php');
        ?>
            <button type='button' href='#agregarColor' class="btn btn-success" data-toggle='modal' data-backdrop='static'>Nuevo</button>
            <br/>
            <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered table-condensed" id="colores">
                <thead>
                    <tr>
                        <th>Color</th>
                    </tr>
                </thead>
                <tbody>
<?php
                    while($fila = mysql_fetch_array($consulta)){
                        $id = $fila['idColor'];
                        echo "<tr>";
                            echo "<td>";
                            include('modal_edit_color.php');
                                echo "<button type='button' href='#editarColor".$id."' id='".$id."' class='btn btn-default btn-xs' data-toggle='modal' data-backdrop='static'>".$fila['nomColor']."</button>";
                            echo "</td>";
                        echo "</tr>";
                    }
?>
                </tbody>
            </table>
        </div>
        <br/><br/>

        <script>
            $('.modal').on('shown.bs.modal', function() {
              $(this).find('input:eq(1)').focus();
            });
        </script>
    </body>
    </html>

modal_add_color.php

 <?php
    if(isset($_POST['submit'])){
        require_once '../../class/query_color.php';

        $nomColor = $_POST['nomColor'];

        $objColor = new Color;
        $objColor->alta_color($nomColor);
    }else{
?>
        <!DOCTYPE HTML>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
            <script type="text/javascript" src="../../class/ajaxColor.js"></script>

        </head>
        <body>
            <div id="agregarColor" class="modal fade" role="dialog" data-keyboard="false">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h2 class="modal-title">Agregar color</h2>
                        </div>
                        <form id="formularioAltaColor" name="formularioAltaColor" method='post' action="modal_add_color.php" onsubmit="altaColor(); return false">
                        <input type="hidden" name="submit" value="">
                        <div class="modal-body">
                            <table class="modal-table">
                                <tr>
                                    <td><label>Color</label></td>
                                    <td><input type='text' name='nomColor' class="form-control focusedInput" onfocus="this.value = this.value;" maxlength="30" required></td>
                                </tr>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
                            <button type="submit" name="submit" id="submit" class="btn btn-primary" value="submit">Guardar cambios</button>
                        </div>
                        </form>
                    </div>
                </div>
            </div>
        </body>
    </html>
<?php
    }
?>

ajaxColor.php

function altaColor(){
var dataString = $('#formularioAltaColor').serialize();
var table = $('#colores').DataTable();

$.ajax({
    url: 'modal_add_color.php',
    type: "POST",
    data: dataString,
    success: function(datos){
        $('#agregarColor').modal('hide');  

        /*What can I code here to refresh my dataTable without refresh fullpage?*/
    }
})
return false;

}

dataTablesLanguage.js

$(document).ready(function(){
$('#colores').DataTable({
    "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Mostrar _MENU_ registros",
        "sZeroRecords":   "No se encontraron resultados",
        "sEmptyTable":    "Ningún dato disponible en esta tabla",
        "sInfo":          "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
        "sInfoEmpty":     "Mostrando registros del 0 al 0 de un total de 0 registros",
        "sInfoFiltered":  "(filtrado de un total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands": ",",
        "sLoadingRecords":"Cargando...",
            "paginate": {
                "sFirst":    "Primero",
                "sLast":     "Último",
                "sNext":     "Siguiente",
                "sPrevious": "Anterior"

        },
            "aria": {
                "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        },
        //"responsive": true,
        "iDisplayLength": 50
    });
});

query_color.php

<?php
require_once 'connection.php';

class Color{

    private $conn;

    function color(){
        $this->conn = new Connection;
    }

    function select_color(){
        $result = NULL;
        if($this->conn->connect() == true){
            $query = "SELECT idColor, nomColor FROM color ORDER BY nomColor ASC";
            $result = mysql_query($query);
        }
        $this->conn->disconnect();
        return $result;
    }

    function alta_color($campo){
        $resultado = NULL;
        if($this->conn->connect() == true){
            $query = "INSERT INTO color (nomColor) VALUES ('".mysql_real_escape_string($campo)."')";
            $result = mysql_query($query);
        }
        $this->conn->disconnect();
        return $result;
    }
    }
?>

And it works fine, it insert data without problem, but I want to omit the part of reloading the fullpage to see inserted data.


To refresh datatables use the draw() function. For this to work however, you need to update the datatables data object. For instance you can use the cell.data() function if you need to update the data in a single cell:

var table = $('#colores').DataTable();

$.ajax({
    url: 'modal_add_color.php',
    type: "POST",
    data: dataString,
    success: function(datos){
        $('#agregarColor').modal('hide');
        cell = table.cell($('jquery-selector-here'));
        cell.data('new-cell-data-here');
        table.draw();
    }
})

Updating the table html directly is not advised as the new data will not be seen by datatables. You need to update datatables through it's API and then redraw the table.