Doubt about passing variables from jquery to php

0

I'm trying to pass several variables taken from a calendar from jquery as soon as you click on a certain date in the calendar. When clicked, throw the date into an input with id="my_hidden_input"

$('#datepicker').on('changeDate', function() {
        $('#my_hidden_input').val(
            $('#datepicker').datepicker('getFormattedDate')
        );
        var fecha = $('#my_hidden_input').val();
        console.log(fecha);
        var dia_fecha = fecha.slice(0,2);
        console.log(dia_fecha);
        var mes_fecha = fecha.slice(3,5);
        console.log(mes_fecha);
        var anyo_fecha = fecha.slice(6,10);
        console.log(anyo_fecha);
        $.ajax({
            beforeSend: function (){
            },
            url: "horarios.php" ,
            type: "post",
            data: {dia_f:dia_fecha, mes_f:mes_fecha, anyo_f: anyo_fecha},
            sucess: function (resp){
                console.log(resp)
            },
            error: function (jqXHR, estado, error){
                console.log(estado);
                console.log(error);
            },
            complete: function (jqXHR, estado){
                console.log(estado);
            },
            timeout: 10000
        });


    });


Then, to obtain the variable in the file horario.php:

$dia_fech = $_POST['dia_f'];
  

I get the following error: Notice: Undefined index: dia_f in   /home/u743999068/public_html/abm/horarios.php on line 68

In console I get the following:

07/20/2018 twenty 07 2018 success

PHP Code:

<html lang="es">
<head>
    <meta charset="UTF-8">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="calendario/css/bootstrap-datepicker.css" rel="stylesheet">
    <link href="calendario/css/bootstrap-datepicker.min.css" rel="stylesheet">
    <link href="calendario/css/less/datepicker.less" rel="stylesheet">
    <link href="calendario/css/build/build.less" rel="stylesheet">
    <title>Mi horario</title>
</head>
<body>
   <div class="container">
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#miMenu">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a href="../login-register/index2.php" class="navbar-brand">Bienvenido usuario
                <?php
                    session_start();
                    echo $_SESSION['usr_name'];
                    ?>
                </a>
            </div>      
            <div class="collapse navbar-collapse" id="miMenu">
                <ul class="nav navbar-nav">
                    <li><a href="edit_form2.php">Perfil</a></li> 
                    <li class="active"><a href="horarios.php">Horarios</a></li> 

                    <li><a href="../login-register/logout.php"><span class="label label-danger">CERRAR SESION </span></a></li>                              
                </ul>
            </div>
        </div>
    </nav>
</div>
<div class="container">
<div class="panel panel-default">
    <div class="panel-heading">HORARIO</div>
    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>HORAS</th>                          
                    <th>ACCION</th>             
                </tr>
            </thead>
            <tbody>
                <?php
                     require('conexion.php');
                     $user=$_SESSION['usr_name'];
                     $result=mysqli_query($conexion,"SELECT id_cita FROM citas where nombre_cita='$user'");
                     $cita=mysqli_fetch_array($result);
                     $codcita=$cita['id_cita'];
                     if ($codcita==0){
                        ?>
                            <div class="container">
                                <div id="datepicker" ></div>
                                <input type="hidden" id="my_hidden_input">
                            </div>
                        <?php
                         $dia_fech = $_POST['dia_f'];
                         $result=mysqli_query($conexion,"SELECT * FROM horarios where dia='$dia_fech'");
                         while ($horarios=mysqli_fetch_array($result)){
                             $id=$horarios['id'];                        
                             if ($horarios['Cliente']==null){
                         /*echo "<tr><td id='id:$id' class='cam_editable'>".$horarios['id']."</td>";*/
                         echo "<td id='horas:$id' class='cam_editable'>".$horarios['horas']."</td>";                                            
                         echo"<td id='$id' name='$user' button='true'><button type='button' class='btn btn-success'><span class='glyphicon glyphicon-pencil'></span> Apartar</button></td>";
                         echo"</tr>";
                             }
                         }
                     }else{
                         $result=mysqli_query($conexion,"SELECT * FROM horarios where Cliente='$user'");
                         while ($horarios=mysqli_fetch_array($result)){
                             $id=$horarios['id'];
                             /*echo "<tr><td id='id:$id' class='cam_editable'>".$horarios['id']."</td>";*/
                             echo "<td id='horas:$id' class='cam_editable'>".$horarios['horas']."</td>";

                             echo"<td id='$id' name='$user' button='false'><button type='button' class='btn btn-danger'><span class='glyphicon glyphicon-remove'></span> Cancelar Cita</button></td>";
                             echo"</tr>";
                         }
                     }
                ?>
            </tbody>    

        </table>
    </div>
    </div>
    </div>
<script src="js/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="js/maincita.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="calendario/js/bootstrap-datepicker.js"></script>
<script src="calendario/locales/bootstrap-datepicker.es.min.js"></script>
<script src="js/calendario.js"></script>

</body>

Greetings and thanks!

    
asked by Juan Luis Miras Moreno 03.07.2018 в 22:01
source

1 answer

2

Juan Luis, try putting your Ajax petition like this:

    var request = $.ajax({
        url: "horarios.php",
        data: {
            dia_f: dia_fecha,
            mes_f: mes_fecha,
            anyo_f: anyo_fecha
        },
        method: "post",
        timeout: 10000 
    });

    request.done(function(resp) {
        console.log(resp);
    });

    request.fail(function(jqXHR, estado, error) {
        /*Aquí manejas el timeout*/
        if(estado=='timeout'){
            console.log('Ocurrió timeout... hacer lo que requieras');
        }else{
            console.log('Otro tipo de error ocurrió: '+ estado + " " + error);
        }
    });

    request.always(function(jqXHR, textStatus) {
        console.log(textStatus);
    });

Probably the timeout is giving you problems.

Also, success, error, complete are obsolete since jQuery 3, that's why I changed them to done, fail, always ( see the notes here ). The same happens with type , it is for old versions of jQuery, you should use method .

Comprehension problem about the operation of Ajax

I will try to explain here briefly how Ajax requests work, since I see a serious comprehension problem in that sense and in comments it is complicated to explain it.

The first thing to be clear about Ajax requests is that there are two sides: the client side and the server side .

  • On the client side:
    • you will have a full DOM (HTML / PHP / Javascript), with all the libraries that you require, with forms or other elements to collect the data that the client (through user actions) will send to the server. These data are the ones you send in the data parameter of the Ajax request.
    • you will also have, eventually, a container, a div for example, that you will update dynamically showing information brought from the server or displaying messages based on what happened on the server. That container will be updated from block done of the Ajax request.
  • On the server side:
    • you will have a file that runs on the server (for example horarios.php in your case) that will only be responsible for receiving the information you send from the client, will process it and return information based on what happened.
    • that file can not be a full DOM (HTML / PHP / Javascript), have libraries, bootstrap, etc, etc, etc. That file is just a utility file to receive information from the client, process that information and return the result in a simpler format for the client to process it back, showing its contents in a container yours for example.

The structure is as follows, explained in a simple way.

  • On the client :
  • You will have a file with all its components and libraries. Like this, presented in a very basic way. It is in this file where the Ajax petition is:

    <html>
    
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title>Archivo del cliente</title>
    
            <!-- Librerías aquí como jQuery, Bootstrap, etc -->
    
            <script>
                    /*
                       *... aquí todas las variables que requieras
                       *... y que has tomado de los elementos del DOM  
                       *Y luego, tu petición Ajax
                    */
    
                    var request = $.ajax({
                        url: "horarios.php",
                        data: {
                            dia_f: dia_fecha,
                            mes_f: mes_fecha,
                            anyo_f: anyo_fecha
                        },
                        method: "post",
                        dataType: 'json',
                        timeout: 10000 
                    });
    
                    request.done(function(resp) {
                        console.log(resp);
                        /*
                            *Aquí se muestra en el contenedor info lo que trajo el servidor
                            *Dependiendo de cómo venga la información...
                            *si por ejemplo es solamente un mensaje de información
                            *harías simplemente esto:*
                        */
                        $("#info").html(resp);
    
                        /*
                            *Si el servidor trae algo más, por ejemplo un JSON con 
                            *una o varias filas de datos
                            *entonces tendrías que parsear ese JSON, 
                            *construir una tabla con él y mostrarla
                            *o bien llenar los elementos de un formulario
                            *con los datos del JSON, etc, etce
                        */              
    
                    });
    
                    request.fail(function(jqXHR, estado, error) {
                        /*Aquí manejas el timeout*/
                        if(estado=='timeout'){
                            console.log('Ocurrió timeout... hacer lo que requieras');
                            $("#info").html('Ocurrió timeout... hacer lo que requieras');
                        }else{
                            console.log('Otro tipo de error ocurrió: '+ estado + " " + error);
                            $("#info").html('Otro tipo de error ocurrió: '+ estado + " " + error);
                        }
                    });
    
                    request.always(function(jqXHR, textStatus) {
                        console.log(textStatus);
                    });
            </script>
    
        </head>
        <body>  
            <!-- Aquí elementos para recoger datos, como formularios, datepicker o lo que sea -->
    
            <div id="info">
                <!-- MUY IMPORTANTE -->
                <!-- Este es el contenedor que se usará para mostrar las actualizaciones traídas desde el servidor mediante Ajax -->
    
            </div>
        </body>
    
    </html>
    
  • On the server :
  • You will have a file that will only be an intermediary. No bookstores in it, nothing to get on the screen anything other than what the customer has requested. This file must exist as a bridge between the client and the server, to fetch and carry data . The one in charge of formatting and presenting the data is the other file, the one that sent the request.

    That is, that your file horarios.php would have a structure like this, more or less:

    <?php
    
        $laFecha=(empty($_POST["dia_f"])) ? NULL : $_POST["dia_f"] ;
        $arrResultado=array();
        if ($laFecha){
    
            /*
                *Lanzar por ejemplo una consulta a la base de datos 
                *usando como criterio $laFecha, 
                *recoger los datos, meterlos en un arreglo
                *y devolverlos
            */
            $datosObtenidos=array("cliente"=>"Pedro", "balance"=>5000); //Este es un resultado imaginario
            $arrResultado=$datosObtenidos;
    
        }else{
    
            $arrResultado["error"]="La fecha no fue enviada en el POST";    
    
        }
    
        echo json_encode($arrResultado);
    
    ?>
    

    The UNIQUE that that file shows on the screen is the data that is in $arrResultado in the form of a JSON. That data can be what has been brought from the database, or an error message either.

    If the query is successful, you will have that JSON in variable resp of done of the Ajax request, then you must parse that information and present it as you want in the container info the client's. It does not matter what you need to present: a table, a form, a calendar, a complete book ... whatever, whatever it takes. You must return it from the server in an appropriate format and handle it in done .

    The PHP file would then be something like this:

    <?php
    
        $laFecha=(empty($_POST["dia_f"])) ? NULL : $_POST["dia_f"] ;
        $arrResultado=array();
        if ($laFecha){
    
            /*
                *Lanzar por ejemplo una consulta a la base de datos 
                *usando como criterio $laFecha, 
                *recoger los datos, meterlos en un arreglo
                *y devolverlos
            */
            $datosObtenidos=array("cliente"=>"Pedro", "balance"=>5000); //Este es un resultado imaginario
            $arrResultado=$datosObtenidos;
    
        }else{
    
            $arrResultado["error"]="La fecha no fue enviada en el POST";    
    
        }
    
        echo json_encode($arrResultado);
    
    ?>
    

    Simply, I use a ternary operator to verify if in the POST, there is an element called dia_f (this is a very basic example, it does not mean that it has to be exactly like that). If dia_f was posted then I launch for example a query to the database and put the results of that query in the result array. If instead, dia_f was not posted, instead of database results, I put an error message in the array.

    And at the end I print what happened like a JSON.

    If you have understood this, you will understand that Ajax requests are simpler than they may seem. But if you do not understand this, you will not be able to pull all the advantages that Ajax offers.

    I hope you have understood me better now. If you have questions, you can ask in comments.

        
    answered by 03.07.2018 / 23:35
    source