Get values from a table - jquery - ajax

1

How can I go through the rows of an HTML table and get the values of a cell with a button?
I am making an application in php and I need to send some data obtained from a table through ajax to another php file. I have already obtained the value of a specific cell, the problem is that when I send it, I am not receiving one of the data specifically:

idcita = $(this).html() + "\n";

This is the error that shows me:

  

Notice: Undefined index: idcita in C: \ xampp \ htdocs \ uci_citas \ model_table.php on line 3

These are the files I'm handling:

Script:

<script>
        $(document).ready(function() {
        $('.enviar').on('click', function() {
            /*var tags_td = new Array();
            var tags_td=document.getElementsByName('n');
            var att = document.getElementsByName('atendido');
            var celda = 0;*/
            var idcita = "";
            var atendido = $("#atendido").val();

            // Obtenemos todos los valores contenidos en los <td> de la fila
            // seleccionada
            $(this).parents("tr").find(".n").each(function() {
              idcita = $(this).html() + "\n";
            });

            console.log(idcita);

            $.ajax({
                    data:  {idcita:idcita, atendido:atendido}, //datos que se envian a traves de ajax
                    url:   'modelo_tabla.php', //archivo que recibe la peticion
                    type:  'POST', //método de envio
                    success:  function (response) {
                        location.href='citas.php';
                    }
            });
        });
    });
    </script>

functions.php:

<?php
    function tabla(){
        try {
            include_once("conexion.php");
            $fecha = date('Y-m-d');
            $stmt = $con_bd->prepare('SET max_join_size=18446744073709551615');
            $stmt->execute();
            $stmt = $con_bd->prepare('SELECT * FROM solicitar_cita WHERE dia = :dia ORDER BY hora ASC');
            $stmt->bindParam(':dia', $fecha);
            $stmt->execute();
            $rs = $stmt->fetchAll();
            $i = -1;

            if (!empty($rs)) {
                $tabla = "<table class='table table-hover table-responsive' id='tabla_datos'>
                            <thead>
                                <tr class='bg-primary'>
                                    <th scope='col'>ID</th>
                                    <th scope='col'>Nombre</th>
                                    <th scope='col'>Apellido</th>
                                    <th scope='col'>Identificacion</th>
                                    <th scope='col'>Celular</th>
                                    <th scope='col'>Direccion</th>
                                    <th scope='col'>Correo</th>
                                    <th scope='col'>Hora</th>
                                    <th scope='col'>Atendido</th>
                                    <th scope='col'>Boton</th>
                                </tr>
                            </thead>";
                            "<tbody>";
                foreach ($rs as $resultado) {
                    $i = $i+1;
                    $val = ($resultado['atendido'] == 1) ? 1 : 1;
                    $tabla .= "<tr>
                                    <td class='n'>".$resultado['idsolicitar_cita']."</td>
                                    <td>".$resultado['nombre']."</td>
                                    <td>".$resultado['apellido']."</td>
                                    <td>".$resultado['identificacion']."</td>
                                    <td>".$resultado['celular']."</td>
                                    <td>".$resultado['direccion']."</td>
                                    <td>".$resultado['correo']."</td>
                                    <td>".$resultado['hora']."</td>
                                    <td>".$retVal = ($resultado['atendido'] == 1) ? 'Si' : 'No'."</td>
                                    <input type='hidden' id='atendido' name='atendido' value=".$val.">
                                    <input type='hidden' id='idu' name='idu' value=".$resultado['idsolicitar_cita'].">
                                    <td><button id='enviar' name='enviar' class='enviar'><img src='img/checkmark.png' width='15px' height='15px' ".$Val = ($resultado['atendido'] == 1) ? 'disabled' : 'enabled'."></button></td>
                                </tr>";
                }
                $tabla .= "</tbody>
                        </table>";
            }
            echo $tabla;    
        } catch (PDOException $e) {
            echo 'Error: ' . $e->getMessage(). '<br/>';
        }
    }
?>

template_table.php

<?php
    $atendido = $_POST['atendido'];
    $idu = $_POST['idcita'];
    try {
        include_once("conexion.php");
        $stmt = $con_bd->prepare('UPDATE solicitar_cita SET atendido = :atendido WHERE idsolicitar_cita = :idu');
        $stmt->bindParam(':atendido', $atendido);
        $stmt->bindParam(':idu', $idu);
        $rows = $stmt->execute();
        $com = '';
        if ($rows) {
            $com = 'completado';
            echo $com;
        }       
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
    }
?>
    
asked by Jesanq 22.03.2018 в 00:02
source

2 answers

1

I thank @ JavierGarcía for offering their help, Finally, I was able to find the problem, what happened was that the default action of the event affected the sending of the data, I just needed to implement the line:

e.preventDefault();

With that I work perfectly, I leave the code of the three files as they are working, for those who have the same problem:

script:

<script>
$(document).ready(function() {
    $('#tabla_datos').on('click', '.enviar', function(e) {

        e.preventDefault(); // cancela el evento por defecto ***MUY IMPORTANTE PARA EL FUNCIONAMIENTO**

        var filaactual = $(this).closest("tr"); // obtiene la fila actual

        var cita = filaactual.find("td:eq(0)").text(); // obtiene el valor del primer TD de la fila actual

        var atendido = $("#atendido").val();


        var parametros = {
            cita: cita,
            atendido: atendido
        };

        $.ajax({
            type:  'POST', //método de envio
            data:  parametros, //datos que se envian a traves de ajax
            url:   'modelo_tabla.php', //archivo que recibe la peticion
            success:  function (response) {
                        location.href='citas.php';
                      }
        });
    });
});
</script>

functions.php

<?php
    function tabla(){
        try {
            include_once("conexion.php");
            $fecha = date('Y-m-d');
            $stmt = $con_bd->prepare('SET max_join_size=18446744073709551615');
            $stmt->execute();
            $stmt = $con_bd->prepare('SELECT * FROM solicitar_cita WHERE dia = :dia ORDER BY hora ASC');
            $stmt->bindParam(':dia', $fecha);
            $stmt->execute();
            $rs = $stmt->fetchAll();
            $i = 0;

            if (!empty($rs)) {
                $tabla = "<table class='table table-hover table-responsive' id='tabla_datos'>
                            <thead>
                                <tr class='bg-primary'>
                                    <th scope='col'>ID</th>
                                    <th scope='col'>Nombre</th>
                                    <th scope='col'>Apellido</th>
                                    <th scope='col'>Identificacion</th>
                                    <th scope='col'>Celular</th>
                                    <th scope='col'>Direccion</th>
                                    <th scope='col'>Correo</th>
                                    <th scope='col'>Hora</th>
                                    <th scope='col'>Atendido</th>
                                    <th scope='col'>Boton</th>
                                </tr>
                            </thead>";
                            "<tbody>";
                foreach ($rs as $resultado) {
                    $i = $i+1;
                    $val = ($resultado['atendido'] == 1) ? 1 : 1;
                    $tabla .= "<tr>
                                    <td class='n'>".$resultado['idsolicitar_cita']."</td>
                                    <td>".$resultado['nombre']."</td>
                                    <td>".$resultado['apellido']."</td>
                                    <td>".$resultado['identificacion']."</td>
                                    <td>".$resultado['celular']."</td>
                                    <td>".$resultado['direccion']."</td>
                                    <td>".$resultado['correo']."</td>
                                    <td>".$resultado['hora']."</td>
                                    <td>".$retVal = ($resultado['atendido'] == 1) ? 'Si' : 'No'."</td>
                                    <input type='hidden' id='atendido' name='atendido' value=".$val.">
                                    <td><button id='enviar' name='enviar' class='enviar'><img src='img/checkmark.png' width='15px' height='15px' ".$Val = ($resultado['atendido'] == 1) ? 'disabled' : 'enabled'."></button></td>
                                </tr>";
                }
                $tabla .= "</tbody>
                        </table>";
            }
            echo $tabla;    
        } catch (PDOException $e) {
            echo 'Error: ' . $e->getMessage(). '<br/>';
        }
    }
?>

template_table.php

<?php
    $atendido = $_POST['atendido'];
    $idcita = $_POST['cita'];
    try {
        include_once("conexion.php");
        $stmt = $con_bd->prepare('UPDATE solicitar_cita SET atendido = :atendido WHERE idsolicitar_cita = :idcita');
        $stmt->bindParam(':atendido', $atendido);
        $stmt->bindParam(':idcita', $idcita);
        $rows = $stmt->execute();
        $com = '';
        if ($rows) {
            $com = 'completado';
            echo $com;
        }       
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
    }
?>


I leave a link of two pages that were very helpful to solve this problem:

jQuery How to Get Table Cell Value TD Value [4 ways]

Receiving Multiple Parameters into PHP from jQuery Ajax Call

    
answered by 23.03.2018 / 04:22
source
0

Your idcita variable will store only the last value of the elements with class .n, if you require a single value access: $(this).parents("tr").find("#idelemento") Otherwise if you are going to go make sure to concatenate idcita += $(this).text()

I see the correct ajax, check the network tab of your browser and see if the idcita value is present in the request.

Try recovering in your model with $_REQUEST['idcita']

    
answered by 22.03.2018 в 00:53