如何使用php + html + ajax删除行?

时间:2018-07-07 22:38:58

标签: javascript php mysql ajax materialize

我一直试图从HTML表格中删除一行。 我正在使用Materialize CSS

这就是我得到的ID是员工ID Html table, populated with mysql

这是代码

<?php 
  $server = mysql_connect("localhost", "root", ""); 
  mysql_set_charset('utf8', $server);
  $db = mysql_select_db("cursos", $server);
  $query = mysql_query("SELECT * FROM empleados"); 
?>

         <table class="bordered responsive-table highlight">
             <thead>
            <tr>
                <th>ID</th>
                <th>Nombre</th>
                <th>Apellidos</th>
                <th>Cumpleaños</th>
                <th>Género</th>
                <th>Nacionalidad</th>
                <th>Despedir</th>
            </tr>
</thead>
            <?php
               while ($row = mysql_fetch_array($query)) {
?>
             <tbody>
                    <tr>
                        <td><?php echo $row['empleado_id']; ?></td>
                        <td><?php echo $row['nombre']; ?></td>
                        <td><?php echo $row['apellidos']; ?></td>
                        <td><?php echo $row['fecha_nac']; ?></td>
                        <td><?php echo $row['genero']; ?></td>
                        <td><?php echo $row['nacionalidad']; ?></td>
                            <?php

                            $empleado_id = $row['empleado_id'];                         
                                    ?>
                        <td><a id="<?php echo $empleado_id; ?>" name="borrar" class="btn-floating btn-small waves-effect waves-light red"><i class="material-icons">delete</i></a></td>
                    </tr>
             </tbody>
    <?php
               }

            ?>
        </table>

我希望能够单击该红色按钮并将查询发送到SQL。

到目前为止,这就是我所拥有的

<td><a id="<?php echo $empleado_id; ?>" name="borrar" class="btn-floating btn-small waves-effect waves-light red"><i class="material-icons">delete</i></a></td>

通过使用id="<?php echo $empleado_id; ?>",红色按钮的ID始终是员工ID。

如何将按钮ID传递给执行查询的功能?

1 个答案:

答案 0 :(得分:1)

在这样的标记中

设置onClick属性:

<td><a onClick="deletThis(this.id)" id="<?php echo $empleado_id; ?>" name="borrar" class="btn-floating btn-small waves-effect waves-light red"><i class="material-icons">delete</i></a></td>

现在在脚本标签的文件末尾执行以下功能

<script>
   function deletThis(employeeId){
      //for surity if the value ir right u can chech in console
      console.log(employeeId);
      //now make an AJAX request to your file let's say delete.php
      $.post("./delete.php",
         {
           employeeId : employeeId
         },
         function(response, status){
             console.log(response);
         });
      }
</script>

现在与此文件同时创建一个delete.php文件,并编写php代码以删除类似这样的条目

<?php

   $employeeId = $_POST['employeeId'];

   //delte from db

?>