Mysql query from Javascript with Ajax

1

I wanted to know how I can make a Mysql query at a specific time with this watch that I have in Javascript. I understand that you have to use Ajax, but I have tried to include the Ajax part inside the if of the time I want, and everything stops working (the clock and the query). Any help?

Thank you very much in advance.

        <!DOCTYPE html>
      <html>
       <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <meta name="viewport" content="width=device-width">
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
         <script>

    function clock(id){ //El parametro id es donde se escribirá la hora

    var seeTime = "2017-10-02 13:42:20"; //fecha y hora de gatillamiento de evento
    var clock = document.getElementById(id); //Asignamos una variable al elemento del documento donde escribiremos la hora

    var Digital=new Date(); //Creamos el objeto Date para obtener la fecha completa
    var h = Digital.getHours(); //hora
    var m = Digital.getMinutes(); //mins
    var s = Digital.getSeconds(); //segs
    var year = Digital.getFullYear(); //año
    var month = Digital.getMonth()+1; //mes, +1 ya que este metodo da de 0-11 en vez de 1-12
    var day = Digital.getDate(); //dia


    //Agregamos los 0 si son menores a 10
    if(month < 10){ month = "0"+month; }
    if(day < 10){ day = "0"+day; }
    if(h < 10){ h = "0"+h; }
    if(m < 10){ m = "0"+m; }
    if(s < 10){ s = "0"+s; }

    var myTime = year+"-"+month+"-"+day+" "+h+":"+m+":"+s; //Esta variable es para obtener la fecha completa en formato "YYYY-mm-dd HH:mm:ss" PARA GATILLAR EVENTO

    h = parseInt(h); //Volvemos a hacer numerico la hora, ya que concatenmos arriba
    var hs = "PM"; //Damos la premisa que es PM. "hs" de hour system
    if(h > 12){ //Si la hora es mayor que 12.... 
    h -= 12; //Quitamos 12 horas de modo que las 16hr es 16-12=4
    }
    else{ //De no ser así dejamos tal cual y decimos que es AM
    hs = "AM";
    }

    var showTime = h+":"+m+":"+s+" "+hs; //Obtenemos la hora a mostrar "HH:mm:ss AM/PM"
    clock.innerHTML = showTime; //Escribimos hora

        if(myUnixTime(myTime) == myUnixTime(seeTime)){ //Si myTime == seeTime gatillamos evento 
        //Gatillamos evento

         $(function() { //usamos function porque document.ready es deprecated desde jQuery 3

        //Guardamos una variable timer para poder pararla si ocurre error
        var timer = setInterval(update, 1000);

        function update() 
        { 
            //Almacenamos la petición ajax en la variable request
            var request = $.ajax
                ({
                    url: "copia de consulta.php",
                    method: "POST",
                    dataType: "json"
                });


                //Usamos request y evaluamos usando done y fail, es lo recomendado por jQuery
                //done se lanzará cuando la petición Ajax tenga éxito
                request.done(function( datos ) 
                {
                    console.log(datos);

                    // Creamos una variable y evaluamos datos
                    var txtHTML;
                    if (!datos.error)
                    {
                       //Si se espera más de una fila hay que leer datos en un bucle
                        /*txtHTML=datos.ID+"<br />"+datos.nombre;*/

                        $.each(datos, function(key, value) 
                            { 
                                txtHTML +=key + ": " + value; 
                            });

                     }else{
                        txtHTML=datos.error;
                        clearInterval(timer); //paramos el timer
                     }
                     $('#contenedor').text(txtHTML);
                });

                //fail se lanzará cuando la petición Ajax falle      
                request.fail(function( jqXHR, textStatus ) 
                {
                    alert( "Falló la petición Ajax: " + textStatus );
                    //Paramos el timer
                    clearInterval(timer); 
                });

            }

    });

        //document.getElementById('liveclock').innerHTML = "Hello World!";

        }
    }


    function myUnixTime(d){ //Esta funcion obtiene los segundos de una fecha dada en formato "YYYY-mm-dd HH:mm:ss" en este caso la fecha es el parametro "d"
    var mArr = [31,28,31,30,31,30,31,31,30,31,30,31]; //Cantidad dias de c/mes

    var spl = d.split(" "); //Separamos la fecha de la hora spl[0] = fecha, spl[1] = hora
    var date = spl[0].split("-"); //Separamos los datos de la fecha date[0] = año, date[1] = mes, date[2] = dia

    // Es necesario usar parseInt() para obtener el valor numerico de los datos
    var y = parseInt(date[0])*365*24*60*60; //Agregamos los segundos que tiene un año
    var m = parseInt(date[1]); //Obtenemos el mes, lo usaremos luego
    var d = parseInt(date[2])*24*60*60; //Obtenemos los segundos de un dia

    //Aqui lo que haremos es sumar la cantidad de dias de los meses que han pasado 
    var mAdd = 0; //Los dias se agregaran en esta variable
    for(var k=0;k<m;k++){ //Partimos desde el indice 0 de mArr (cantidad dias/mes) hasta el mes en el que estamos
    mAdd += mArr[k]; //Agregamos a mAdd la cantidad de dias de dias del mes con indice k
    }

    m = mAdd*24*60*60; //Obtenemos la cantidad de segundos del total de meses transcurridos

    var time = spl[1].split(":"); //Separamos los datos de la hora time[0] = hora, time[1] = mins, time[2] = seg

    var h = parseInt(time[0])*60*60; //Agregamos segundos en 1 hora
    var m = parseInt(time[1])*60; //Agregamos segundos en 1 min
    var s = parseInt(time[2]); //...

    return y+m+d+h+m+s; //retornamos la suma de todos los segundos obtenidos
    }


    window.onload=function(){ //Cuando la ventana cargue...
    setInterval("clock('liveclock')",1000); //Creamos un intervalo de 1000ms a la funcion myClock, ms= mili segundos, 1000ms = 1s
    };

    </script>
    <div class="reloj">
              <br><span class="clock" id="liveclock"></span><br></div>
         <script type="text/javascript">

        </script>

    </head>
    <body>

     <section class="content">
      <p>CONSULTA BASE DE DATOS CADA SEGUNDO</p>
      <p><div id="contenedor">0</div>
     </section>

    </body>
    </html>

The file "query copy.php":

  $mysqli = new mysqli("localhost", "usuario", "contraseña", "nombre bd");
    // verificar la conexión 

    if ($mysqli->connect_errno) {
        $arrRespuesta=array("error"=>"Conexión fallida: ".$mysqli->connect_error);

    }else{

         $consulta = "SELECT * FROM productos";

         if ($resultado = $mysqli->query($consulta)) {
            // obtener un array asociativo 
            $arrRespuesta=array();

            while ($fila = $resultado->fetch_assoc()) {
                $arrRespuesta[]=$fila;
            } 

            // liberar el conjunto de resultados 
            $resultado->free();
         }else{
            $arrRespuesta=array("error"=>"Hubo un problema con la consulta");

         }
        // cerrar la conexión 
        $mysqli->close();
    }


    //Al final de todo imprimimos el JSON que será recogido en la petición //Ajax/jQuery
    $json = json_encode($arrRespuesta);
    header('Content-Type: application/json');
    echo $json;
    
asked by Matrix 22.09.2017 в 20:20
source

1 answer

1

I will point out some problematic parts of your code, providing a solution.

We will also use updated code, according to jQuery's recommendations.

I have commented on the parts of the code where I have made changes.

  

EDITING NOTE :

     
  • We will set the connection charset to UTF-8 to ensure that our JSON will be created without errors.
  •   
  • We will read Ajax's answer within two loops, since we are receiving an associative array.
  •   
  • The var txtHTML=""; must be initialized to "" so you do not give undefined at the beginning.
  •   

jQuery

$(function() { //usamos function porque document.ready es deprecated desde jQuery 3

    //Guardamos una variable timer para poder pararla si ocurre error
    var timer = setInterval(update, 1000);

    function update() 
    { 
        //Almacenamos la petición ajax en la variable request
        var request = $.ajax
            ({
                url: "copia de consulta.php", //¿Ese archivo se llama así realmente?
                method: "POST",
                dataType: "json"
            });


            //Usamos request y evaluamos usando done y fail, es lo recomendado por jQuery
            //done se lanzará cuando la petición Ajax tenga éxito
            request.done(function( datos ) 
            {

                // Creamos una variable y evaluamos datos
                var txtHTML="";
                if (!datos.error)
                {
                    //Si se espera más de una fila hay que leer datos en un bucle
                    //txtHTML=datos.ID+"<br />"+datos.nombre ;

                    $.each(datos, function(i, object) {
                        $.each(object, function(property, value) {
                            txtHTML +=property + "=" + value+"<br />";
                            //Prueba
                            console.log(property + "=" + value+"<br />");
                        });
                        txtHTML +="<hr />";   
                    });

                 }else{

                    txtHTML=datos.error;
                    clearInterval(timer); //paramos el timer
                 }
                 $('#contenedor').text(txtHTML);
            });

            //fail se lanzará cuando la petición Ajax falle      
            request.fail(function( jqXHR, textStatus ) 
            {
                alert( "Falló la petición Ajax: " + textStatus );
                //Paramos el timer
                clearInterval(timer); 
            });

    }

});

PHP

Since jQuery expects a JSON response, which is a very good idea, we will build such a response in PHP code.

It is very important to save a variable and print anything at the end . Therefore, our variable $arrRespuesta will be our only variable, which will take values according to what happens. And we'll print it at the end.

  

EDITING NOTE: Here we only added this line: $mysqli->set_charset("utf8");

$mysqli = new mysqli("host", "usuario", "contraseña", "base de datos");
// verificar la conexión 

if ($mysqli->connect_errno) {
    $arrRespuesta=array("error"=>"Conexión fallida: ".$mysqli->connect_error);

}else{
     /*Establecemos el charset a la conexión para evitar datos erróneos*/
     $mysqli->set_charset("utf8");
     $consulta = "SELECT * FROM productos";

     if ($resultado = $mysqli->query($consulta)) {
        // obtener un array asociativo 
        $arrRespuesta=array();
        while ($fila = $resultado->fetch_assoc()) {
            $arrRespuesta[]=$fila;
        }

        // liberar el conjunto de resultados 
        $resultado->free();

     }else{

        $arrRespuesta=array("error"=>"Hubo un problema con la consulta");

     }

    // cerrar la conexión 
    $mysqli->close();
}



//Al final de todo imprimimos el JSON que será recogido en la petición Ajax/jQuery
$json = json_encode($arrRespuesta);
header('Content-Type: application/json; charset=utf8');
echo $json;
    
answered by 23.09.2017 / 15:09
source