get the form values by ajax and pass it to a query

0

I have a form to filter the data to generate graphs of survey data

<!DOCTYPE html>
    <html>

    <head>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0-rc.1/themes/smoothness/jquery-ui.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
    </head>

    <body>
        <br /><br />

      
        <form id="formulario" class="form-inline" method="post" style="margin-left: 5%;">


          <div class="form-group">
            <label >Seleccione Asignatura:</label>
            <input class="form-control" name="cursos" id="autocomplete">
          </div>


           <div class="form-group">
            <input class="form-control" id="cod_curso" name="cod_curso" style="display:none;">
           </div>

  
           <div id="secciones" class="form-group"></div>
      
 
            <div class="form-group">
                <label for="sel1">Seleccione año:</label>
                <select class="form-control" name="anio" id="anio" placeholder="" required>
                  <option value=2015>2015
                  <option value=2016>2016 
                  <option value=2017>2017 
                  <option value=2018>2018 
                  <option value=2019>2019 
               </select>
            </div>

            <div class="form-group">
                <label for="sel1">Seleccione semestre:</label>
                <select class="form-control" name="semestre" id="semestre" placeholder="" required>
                  <option value=Primer>Primer 
                  <option value=Segundo>Segundo
               </select>
            </div>
            
            <div class="form-group text-center" style="margin-left: 50px;">
                <button id="myButton" type="button" class="btn btn-default">Generar</button>
            </div>

        </form>
        
        <div id="grafico"></div>
    </body>

    </html>

<script src="//code.jquery.com/ui/1.12.0-rc.1/jquery-ui.js"></script>
    <script>
    
$(document).on('ready',function(){       
    $('#myButton').click(function(){
            var url = "grafico_prueba.php";
            $.ajax({                        
            type: "POST",                 
            url: url,                     
            data: $("#formulario").serialize(), 
            success: function(data)
            {
             $('#grafico').html(data);               
           }
       });
    });
});
    

   </script>
    <script>
        var Cursos = [
            <?php
                $query2 = $mysqli -> query ("SELECT DISTINCT cod_ramo FROM cursos");
                $cantidad_cursos = mysqli_num_rows($query2);
				$i = 1;	
            
                while ($valores2 = mysqli_fetch_array($query2)) {
                    echo  "'" . $valores2['cod_ramo'] . "'";
                    if($i < $cantidad_cursos) {
                        echo ", "; 
                        $i++;
                    }
                }
            ?>
        ]


        $("#autocomplete").autocomplete({
            source: Cursos,
            select: function(event, ui) {

                    $.ajax({
                        url: "secciones.php",
                        method: "GET",
                        data: {
                            cod_ramo: ui.item.value
                        },
                        success: function(data) {
                            $('#secciones').html(data);
                        }

                });
            }
        });
    </script>

This form has an ajax to nest subject with sections and another to find the unique key of that course (cod_curso) that is hidden.

and then that input values I need to pass it to a highchart graphic

grafico_prueba.php

<script>    
    
Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Grafico'
    },
    xAxis: {
        min: 0,
        title: {
            text: 'Pregunta'
        }
    },
    xAxis: {
        categories: [   
        <?php 
		$sql = "SELECT * FROM preguntas";
		$result = mysqli_query($mysqli,$sql);
		while ($registros = mysqli_fetch_array($result))
		{
        ?>
            '<?php echo $registros["nombre"] ?>',
        <?php
		}
		?>]
        
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Porcentajes'
        }
    },
    tooltip: {
        pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
        shared: true
    },
    plotOptions: {
        column: {
            stacking: 'percent'
        }
    },
    series: [{
       name: 'no aplica',
        data:  <?php 
				$sql = "FROM preguntas p 
                        
                        LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta 
                        
                        LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo

                        LEFT JOIN form_alumnos f on r.id_form_alumno_fk = f.id_form_alumno 
                        
   WHERE (f.cod_curso_alumno = '$cod_curso' AND f.anio = '$anio' AND f.semestre = '$semestre' or cod_curso_alumno IS NULL or anio IS NULL or semestre IS NULL)  and tr.tipo = '1'
                        
                        GROUP BY p.id_pregunta, tr.tipo";
				$result = mysqli_query($mysqli,$sql);
				?>
                [<?php while ($registros = mysqli_fetch_array($result)){ ?><?php echo $registros["cantidad_respuestas"] ?>, 
                 <?php }?>]
    }, {
        name: 'muy en desacuerdo',
        data:  <?php 
				$sql = "FROM preguntas p 
                        
                        LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta 
                        
                        LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo

                        LEFT JOIN form_alumnos f on r.id_form_alumno_fk = f.id_form_alumno 
                        
   WHERE (f.cod_curso_alumno = '$cod_curso' AND f.anio = '$anio' AND f.semestre = '$semestre' or cod_curso_alumno IS NULL or anio IS NULL or semestre IS NULL)  and tr.tipo = '2'
                        
                        GROUP BY p.id_pregunta, tr.tipo";
				$result = mysqli_query($mysqli,$sql);
				?>
                [<?php while ($registros = mysqli_fetch_array($result)){ ?><?php echo $registros["cantidad_respuestas"] ?>, 
                 <?php }?>]
    }, {
        name: 'en desacuerdo',
        data:  <?php 
				$sql = "FROM preguntas p 
                        
                        LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta 
                        
                        LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo

                        LEFT JOIN form_alumnos f on r.id_form_alumno_fk = f.id_form_alumno 
                        
   WHERE (f.cod_curso_alumno = '$cod_curso' AND f.anio = '$anio' AND f.semestre = '$semestre' or cod_curso_alumno IS NULL or anio IS NULL or semestre IS NULL)  and tr.tipo = '3'
                        
                        GROUP BY p.id_pregunta, tr.tipo";
				$result = mysqli_query($mysqli,$sql);
				?>
                [<?php while ($registros = mysqli_fetch_array($result)){ ?><?php echo $registros["cantidad_respuestas"] ?>, 
                 <?php }?>]
    }, {
        name: 'en acuerdo',
        data:  <?php 
				$sql = "FROM preguntas p 
                        
                        LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta 
                        
                        LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo

                        LEFT JOIN form_alumnos f on r.id_form_alumno_fk = f.id_form_alumno 
                        
   WHERE (f.cod_curso_alumno = '$cod_curso' AND f.anio = '$anio' AND f.semestre = '$semestre' or cod_curso_alumno IS NULL or anio IS NULL or semestre IS NULL)  and tr.tipo = '4'
                        
                        GROUP BY p.id_pregunta, tr.tipo";
				$result = mysqli_query($mysqli,$sql);
				?>
                [<?php while ($registros = mysqli_fetch_array($result)){ ?><?php echo $registros["cantidad_respuestas"] ?>, 
                 <?php }?>]
    }, {
        name: 'muy de acuerdo',
        data:  <?php 
				$sql = "FROM preguntas p 
                        
                        LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta 
                        
                        LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo

                        LEFT JOIN form_alumnos f on r.id_form_alumno_fk = f.id_form_alumno 
                        
   WHERE (f.cod_curso_alumno = '$cod_curso' AND f.anio = '$anio' AND f.semestre = '$semestre' or cod_curso_alumno IS NULL or anio IS NULL or semestre IS NULL)  and tr.tipo = '5'
                        
                        GROUP BY p.id_pregunta, tr.tipo";
				$result = mysqli_query($mysqli,$sql);
				?>
                [<?php while ($registros = mysqli_fetch_array($result)){ ?><?php echo $registros["cantidad_respuestas"] ?>, 
                 <?php }?>]
    }]
});


</script>
<?php
require_once('../conexion.php');
mysqli_query($mysqli,"SET NAMES 'utf8'");

$cod_curso = $_POST['cod_curso'];
$anio  = $_POST['anio'];
$semestre  = $_POST['semestre'];




?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="../Highcharts-6.0.2/code/highcharts.js"></script>
    <script src="../Highcharts-6.0.2/code/themes/grid-light.js"></script>
    
    
    <script src="../Highcharts-6.0.2/code/modules/exporting.js"></script>
       <script src="https://code.highcharts.com/modules/export-data.js"></script>
</head>
<body style="margin: 0">
   
   <div id="container" style="width: 100%; height: 600px; margin: 0"></div>

</body>
</html>

My problem when passing the variable to the php, I do not understand very well how to apply it in the graph and that every time it is filtered by a course change the data of the graph.

Any guidance or help will be well received.

    
asked by claudia24 23.11.2017 в 20:19
source

1 answer

1

I'll leave you this code that you use at some point, it had the same inconvenience, it's very similar to yours, the code is tested and works correctly, adapt it to your needs, and you tell me.

HTML - Selects to filter

<tr>  
    <td width="150" align="right"><font face="arial"><b>AÑO</b></font></td>
    <td>
      <select name="ANO_ACTA" id="ANO_ACTA" autofocus="autofocus">
      <option>Seleccione...</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
      </select>
    </td>
  </tr>

  <tr>
    <td width="150" align="right"><font face="arial"><b>MES</b></font></td>
    <td>
      <select name="MES_ACTA" id="MES_ACTA">
        <option>Seleccione...</option>
        <option value="ENERO">ENERO</option>
        <option value="FEBRERO">FEBRERO</option>
        <option value="MARZO">MARZO</option>
        <option value="ABRIL">ABRIL</option>
        <option value="MAYO">MAYO</option>
        <option value="JUNIO">JUNIO</option>
        <option value="JULIO">JULIO</option>
        <option value="AGOSTO">AGOSTO</option>
        <option value="SEPTIEMBRE">SEPTIEMBRE</option>
        <option value="OCTUBRE">OCTUBRE</option>
        <option value="NOVIEMBRE">NOVIEMBRE</option>
        <option value="DICIEMBRE">DICIEMBRE</option>
      </select>
    </td>   
  </tr>

SCRIPT     

jQuery(function ($) {

  var chart = new Highcharts.Chart({
    chart: {

        //Nombre del div contenedor
        renderTo: 'container',
        type: 'spline'
    },

    title: {
      text: '<b></b>Seleccione y Año y Mes...</b>'
    },

    subtitle: {
        text: 'Informe Rollout Mensual'
    },

    yAxis: {
      title: {
        text: 'Valores en Millones'
      }
    },

    xAxis: {
      //Categorías en duro o estaticas
      categories: ['DIA 1','DIA 2','DIA 3','DIA 4','DIA 5','DIA 6','DIA 7','DIA 8','DIA 9','DIA 10','DIA 11','DIA 12','DIA 13','DIA 14','DIA 15','DIA 16','DIA 17','DIA 18','DIA 19','DIA 20','DIA 21','DIA 22','DIA 23','DIA 24','DIA 25','DIA 26','DIA 27','DIA 28', 'DIA 29', 'DIA 30', 'DIA 31']
    },

    //Series o numero de lineas estadísticas 
    series: [

    {
      name : "CUNDINAMARCA",
      data: [],
      marker: {
      lineWidth: 5,
      lineColor: ''

      }

    },

    {
      name : "VALLE",
      data: [],
      marker: {
      lineWidth: 5,
      lineColor: ''
      }

    },

    {
      name : "CAUCA",
      data: [],
      marker: {
      lineWidth: 5,
      lineColor: '',
      fillColor: ''
      }

    },

    {
      name : "META",
      data: [],
      marker: {
      lineWidth: 5,
      lineColor: '',
      fillColor: ''
      }
    }]
  });

    //Funcion que al cambiar el 'select' llama los datos
    $( "#MES_ACTA" ).change(function() {
    //validamos las fechass
    var ANO_ACTA = $('#ANO_ACTA').val();
    var MES_ACTA = $('#MES_ACTA').val();


    chart.setTitle({text: "<b></b>Facturación del Mes de <b>" + $("#MES_ACTA option:selected").val() + "</b>"});
    chart.setTitle(null, {text: "<b></b>Informe Rollout Mensual Año: <b>" + $("#ANO_ACTA option:selected").val() + "</b>"});
    //chart.setTitle: permite cambiar el dinamicamente el titulo y el subtitulo('null,') declarando el elemento seleccionado(option:selected) 
    $.ajax({
      url: "procesar.php",
      method: "POST",
      data: { ANO_ACTA: ANO_ACTA, MES_ACTA: MES_ACTA},
      dataType: "json"
    })

    .done(function(data) {
      //Impleméntalo para que ver que te arroja en la consola, o visualizar si tiene un erro
      console.log(ANO_ACTA);
      console.log(MES_ACTA);
      console.log(data);

      chart.series[0].setData(data[0]); 
      chart.series[1].setData(data[1]);
      chart.series[2].setData(data[2]);  
      chart.series[3].setData(data[3]);  
    });
  });
});
</script>

HTML

<table width="1300" border="1" bordercolor="red" align="center">
  <tr>
    <td><div id="container"></div></td>
  </tr>
</table>

PHP

<?php require_once'../Connections/conexion.php';

$MES_ACTA = $_POST['MES_ACTA']; 
$ANO_ACTA = $_POST['ANO_ACTA'];

$resultado = [];
$resultado2 = [];
$resultado3 = [];
$resultado4 = [];

for ($i = 1; $i <= 31; $i++) { 
    $query= "SELECT SUM(VALOR) as total_DIA_1_CUNDINAMARCA FROM rollout_2017 WHERE ANO_ACTA = '$ANO_ACTA' AND MES_ACTA = '$MES_ACTA' AND DIA= '$i' AND DEPARTAMENTO = 'CUNDINAMARCA' AND TIPO_MAT = 'MO'"; 
    $result =  mysql_query($query, $conexion); 
    $valor = mysql_result($result, 0); 
    $resultado[] = round($valor, 1); 
}

for ($i = 1; $i <= 31; $i++) { 
    $query2= "SELECT SUM(VALOR) as total_DIA_1_VALLE_DEL_CAUCA FROM rollout_2017 WHERE ANO_ACTA = '$ANO_ACTA' AND MES_ACTA = '$MES_ACTA' AND DIA = '$i' AND DEPARTAMENTO = 'VALLE DEL CAUCA' AND TIPO_MAT = 'MO'"; 
    $result2 =  mysql_query($query2, $conexion); 
    $valor2 = mysql_result($result2, 0); 
    $resultado2[] = round($valor2, 1); 
}

for ($i = 1; $i <= 31; $i++) { 
$query3= "SELECT SUM(VALOR) as total_DIA_1_CAUCA FROM rollout_2017 WHERE ANO_ACTA = '$ANO_ACTA' AND MES_ACTA = '$MES_ACTA' AND DIA = '$i' AND DEPARTAMENTO = 'CAUCA' AND TIPO_MAT = 'MO'"; 
    $result3 =  mysql_query($query3, $conexion); 
    $valor3 = mysql_result($result3, 0); 
    $resultado3[] = round($valor3, 1); 
}

for ($i = 1; $i <= 31; $i++) { 
    $query4= "SELECT SUM(VALOR) as total_DIA_1_META FROM rollout_2017 WHERE ANO_ACTA = '$ANO_ACTA' AND MES_ACTA ='$MES_ACTA' AND DIA = '$i' AND DEPARTAMENTO = 'META' AND TIPO_MAT = 'MO'"; 
    $result4 =  mysql_query($query4, $conexion); 
    $valor4 = mysql_result($result4, 0); 
    $resultado4[] = round($valor4, 1); 

}
//Si es mas de una "linea" o consulta, tienes que pasar los datos como array
echo json_encode([$resultado, $resultado2, $resultado3, $resultado4]);

?>
    
answered by 23.11.2017 / 22:22
source