How to update ajax php sql server table?

6

Good I'm doing a form but in this case they fill certain data or they choose and a graph is generated and below a table that is basically the description of that graph and it is dynamic.

The problem is that when I press the first time it works fine but when I choose another type the table is not updated and when I click on it several times, the table is updated and it shows me.

could help me.

  

THE PROBLEM IS NOT THE GRAPHIC BUT THE TABLE THAT DOES NOT UPDATE WHEN   I PRESS THE BUTTON

Also, when I enter the default page, the table is displayed as I could do so that when I enter the table is not visible and when I click on it, it will appear

Now I'm on the button that is on my form is the following.

<button type="button" name="btngenerargraficoporterritorio11" class="btn btn-primary" onclick="generargraficodetalleobservacion();">Generar Gráfico</button>

that is to say that when you press you call a function that is for the graphic

<script type="text/javascript">

    function generargraficodetalleobservacion(){

        var grafinicio=document.getElementById("txtgfinicio").value;

        var graffin=document.getElementById("txtgffin").value;

        var zona = document.getElementById("zonalabelidgraf").value;
        var agencia = document.getElementById("agencialabelidgraf").value;
        var tipoobservacion = document.getElementById("tiobselabelidgraf").value;
        var producto = document.getElementById("prodlabelidgraf").value;

        console.log(grafinicio);
        console.log(graffin);
        console.log(zona);
        console.log(agencia);
        console.log(tipoobservacion);
        console.log(producto);

        if(grafinicio=="")
        {
            alert("Ingrese la Fecha inicio");

        }
        if(graffin=="")
        {

            alert("Ingrese la Fecha Fin");
        }
        if(zona=="Seleccionar")
        {
                alert("Ingrese la Zona");

        }
        if(producto=="Seleccionar")
        {
            alert("Ingrese el Producto");
        }
        //listarUsuarios1();
        //$("#tableUsersss").empty().load("Tablahistoricografico.php");


        var options = {

            chart: {
                renderTo: 'containergrafico',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: ' '
            },
            tooltip: {
                formatter: function() {
                    return '<b>' + this.point.name + '</b>: ' + this.y +'%';
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function() {
                            return '<b>' + this.point.name + '</b>: ' + this.y +'%';
                        }
                    },
                    showInLegend: true
                }
            },
            series: []
        };

        $.getJSON("data/detalleobservaciongrafico.php?finicio="+grafinicio+"&ffin="+graffin+"&zona="+zona+"&agencia="+agencia+"&tipoobservacion="+tipoobservacion+"&producto="+producto, function(json) {
                                                                                    options.series = json;
                                                                                    chart = new Highcharts.Chart(options);
                                                                                });
        listarUsuarios1();
                                                                            };

</script>

Now I to generate the table I do with this script

<script>
      /* Por lo que veo usas jQuery */
      function listarUsuarios1() {
         $.ajax({
           type: 'POST',
           url: 'Tablahistoricografico.php',
           dataType  : 'html',
           success: function(data){
             $('#tableUsersss').html(data);
           }
         });
      }  // listarUsuarios

      /* Segun prefieras o estes más familiazado usa este */

      $(function () {
        listarUsuarios1();
      }); 
      /* ó; deseable no dejes ambos solo uno */ 
      $(document).ready(function () {
        listarUsuarios1();
      }); 

</script>

that on my page that calls is this. HISTORICAL TABLE

<?php
include("config.php");
session_start();
   /* Tu proceso de conexión, consulta y resultado */
$finicio = isset($_SESSION['finicio']) ? $_SESSION['finicio'] : '';
$ffin = isset($_SESSION['ffin']) ? $_SESSION['ffin'] : '';
$zona= isset($_SESSION['zona']) ? $_SESSION['zona'] : '';
$agencia = isset($_SESSION['agencia']) ? $_SESSION['agencia'] : '';
$tipoobservacion = isset($_SESSION['tipoobservacion']) ? $_SESSION['tipoobservacion'] : '';
$producto = isset($_SESSION['producto']) ? $_SESSION['producto'] : '';

$sql1 = "EXEC Sp_DetalleObservacion 2,'$finicio','$ffin','$zona','$agencia','$tipoobservacion','$producto','' ";
$result1 = sqlsrv_query($conn,$sql1) or die("Couldn't execut query");

   $sql= "EXEC Sp_DetalleObservacion 7,'','','','','','','' ";
  $result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");    

   if(!$result){
       echo "Ocurrio un error en la consulta"; 
   }else{
       $tabla ="<table class='table table-bordered text-center'>";
       $tabla .="<thead>";
       $tabla .= "<tr>";
       $i = 0;
       while  ($data = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)) {
          if ($i == 0) {
            foreach($data as $key => $value) {                
              $tabla .="<th scope='col' style='text-align: center;background-color: #054AC4;color: #fff'>" . utf8_decode($key) . "</th>";
            }
            $tabla .="</tr>";
            $tabla .="</thead>";

            $tabla .="<tbody>";
          } 
          $tabla .="<tr>";
          foreach($data as $key => $value) {                         
             $tabla .="<td>".utf8_encode($value)."</td>";
          }    
          $tabla .="</tr>";
          $i++;
       }
       $tabla .="</tbody>";
       $tabla .="</table>";
       echo $tabla;
   }       
?>

Image where I send the session

    
asked by PieroDev 26.07.2018 в 17:02
source

1 answer

2

Here is a possible answer to your question.

  

This answer is an example adapted slightly for    es.stackoverflow , you can deactivate or delete the code snippets   referring to this arrangement.

     

The final version requires a form with the input indicated in the   Question to work out of the example simulation .

     

To view the solution correctly , use the mode   "Full page" when running the solution from stackoverflow

DESCRIPTION

  • The getJSON methods have been modified by AJAX.
  • Error control of AJAX requests has been implemented. The error will inform in case of error in the server, showing its response code and body of the same.
  • You must take into account that, in order for the example to work, the receiving containers of the table and the graphic can not be the same or contain each other, or one of them will step on the other.
  • The table was deactivated initially.
  • Each of the functions has been structured so that they are easy to understand and adapt to the final code.
  • The code has been commented and implemented together with an example for es.stackoverflow.com

SOLUTION

// Comentar fuera de es.stackoverflow
// El documento debe contener el formulario de recogida de datos para el gráfico
var es = {};es.stackoverflow = true;

// obtener
function obtener() {
  obtenerGrafico();
  obtenerTabla();
}

// renderizar gráfico
function renderizarGrafico(options) {
  console.log('Grafico');
  if(typeof chart === 'undefined') {
    console.log(' - Generando gráfico');
    chart = new Highcharts.Chart(options);
  }else{
    console.log(' - Actualizando gráfico');
    //chart.update(options);
  }
}

// renderizar tabla
function renderizarTabla(html) {
  console.log('Tabla!');
  console.log(' - Renderizando tabla');
  $('#tableUsersss').html(html);
}

// obtener gráfico
function obtenerGrafico(){
        
        // Obtengo la fecha de inicio del gráfico
        var grafinicio = (es.stackoverflow) ? '07/08/2018' :  document.getElementById("txtgfinicio").value;

        // Obtengo la fecha de final del gráfico
        var graffin= (es.stackoverflow) ? '07/08/2018' : document.getElementById("txtgffin").value;

        // Obtengo la zona
        var zona = (es.stackoverflow) ? 'zona-ej' : document.getElementById("zonalabelidgraf").value;
        
        // Obtengo la agencia
        var agencia = (es.stackoverflow) ? 'agencia-ej' : document.getElementById("agencialabelidgraf").value;
        
        // Obtengo el tipo de observación
        var tipoobservacion = (es.stackoverflow) ? 'observacion-ej' : document.getElementById("tiobselabelidgraf").value;
        
        // Obtengo el producto
        var producto = (es.stackoverflow) ? 'producto-ej' : document.getElementById("prodlabelidgraf").value;

        // Info de consola
        console.log('Datos del gráfico:');
        console.log(' - F Ini: ' + grafinicio);
        console.log(' - F Fin: ' + graffin);
        console.log(' - Zona: ' + zona);
        console.log(' - Agencia: ' + agencia);
        console.log(' - Observacion: ' + tipoobservacion);
        console.log(' - Producto: ' + producto);

        // Validación de datos
        if(!grafinicio)
        {
            alert("Ingrese la Fecha inicio");
            return true;
        }
        if(!graffin)
        {
            return true;
            alert("Ingrese la Fecha Fin");
        }
        if(!zona||zona=='Seleccionar')
        {
            alert("Ingrese la Zona");
            return true;
        }
        if(!producto||producto=="Seleccionar")
        {
            alert("Ingrese el Producto");
            return true;
        }


        // Opciones para generar el grafico
        var options = {

            chart: {
                renderTo: 'containergrafico',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: ' '
            },
            tooltip: {
                formatter: function() {
                    return '<b>' + this.point.name + '</b>: ' + this.y +'%';
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function() {
                            return '<b>' + this.point.name + '</b>: ' + this.y +'%';
                        }
                    },
                    showInLegend: true
                }
            },
            series: []
        };
        
        // Datos de la petición
        // Url
        var url = "data/detalleobservaciongrafico.php";
        // data
        var data =
              "finicio="+grafinicio+
              "&ffin="+graffin+
              "&zona="+zona+
              "&agencia="+agencia+
              "&tipoobservacion="+tipoobservacion+
              "&producto="+producto;

        // Si es el ejemplo de stackoverflow no realizo la llamada a obtener gráfico,
        // en su lugar usaremos un ejemplo de la web de Highcharts para obtener la serie
        if(es.stackoverflow) {
            options.series = [{ data: [ ['EJ1', 25], ['EJ2', 80], ['EJ3', 50] ] }];
            renderizarGrafico(options);
        }else{
              
            // Usamos el método AJAX de jquery en vez GETJSON
            // Más información en caso de error
            $.ajax({
              dataType: "json",
              url: url,
              data: data,
              success: function(json){options.series = json; renderizarGrafico(options);},
              error: function(xhr) {
                // Control de errores más detallado
                console.log("Ups! Parece que tenemos problemas con la nave nodriza! No hemos podido obtener el gráfico.")
                console.log(" - resolution code:" + xhr.status);
                console.log(" - response:");
                console.log(xhr.responseText);
              }
            });
        }
}

// Obtener tabla
function obtenerTabla(){

        // Datos de la petición
        // Url
        var url = "Tablahistoricografico.php";    // Ojo, aquí no tienes data/... ¿Es correcto?
        // data
        // var data = "";                         // Aquí si necesio enviar algun dato, entiendo que se almacena en sesión segun tu ejemplo

        // Si es el ejemplo de stackoverflow no realizo la llamada a obtener la tabla
        // en su lugar incluire una tabla ejemplo en html
        if(es.stackoverflow) {
            renderizarTabla(" \
            <table style='width:100% border: 1px solid #000;'> \
            <tr> \
              <td>EJ1</td> \
              <td>25%</td> \
            </tr> \
            <tr> \
              <td>EJ2</td> \
              <td>80%</td> \
            </tr> \
            <tr> \
              <td>EJ</td> \
              <td>50%</td> \
            </tr> \
          </table> \
            ");
        }else{
              
            // Usamos el método AJAX de jquery en vez GETJSON
            // Más información en caso de error
            $.ajax({
              dataType: "html",
              url: url,
              //data: data,
              success: function(html){renderizarTabla(html);},
              error: function(xhr) {
                // Control de errores más detallado
                console.log("Ups! Parece que tenemos problemas con la nave nodriza! No hemos podido obtener la tabla!")
                console.log(" - resolution code:" + xhr.status);
                console.log(" - response:");
                console.log(xhr.responseText);
              }
            });
        }
}
table, th, td {
    border: 1px solid black;
    width: 100%;
}
<!-- highcharts -->
<script src="https://code.highcharts.com/highcharts.js"></script>

<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<!--Form -->
<!-- No implementado en el ejemplo -->

<!-- Boton generar gráfico -->
<button type="button" name="btngenerargraficoporterritorio11" class="btn btn-primary" onclick="obtener();">Generar Gráfico</button>

<!-- Contenedor del gráfico -->
<div id="containergrafico"></div>

<!-- Contenedor de la tabla -->
<div id="tableUsersss"></div>


<!-- 
  Nota: Un contenedor de gráfico debe ser independiente a uno de tabla, no puede uno contener a otro, o se superpondría el resultado
-->
    
answered by 07.08.2018 в 22:28