如何通过单击整行而不是“编辑”按钮来显示模式

时间:2018-10-29 02:35:00

标签: php jquery datatables

我可以通过向按钮添加属性来从数组中获取其对应的ID,我想知道是否可以通过单击整个表格行而不是单击“编辑”按钮来弹出我的模态

通过点击“编辑”按钮来实现我的功能模式:

image

<!--script for fetching data from db-->
<script>
    $(document).ready(function(){
        var dataTable=$('#example').DataTable({
            "processing": true,
            "serverSide":true,
            "ajax":{
                url:"fetch.php",
                type:"post"
            }
        });
    });
</script>
<!--script js for get edit data-->
<script>
    $(document).on('click','#getEdit',function(e){
        e.preventDefault();
        var per_id=$(this).data('id');
        //alert(per_id);
        $('#content-data').html('');
        $.ajax({
            url:'editdata.php',
            type:'POST',
            data:'id='+per_id,
            dataType:'html'
        }).done(function(data){
            $('#content-data').html('');
            $('#content-data').html(data);
        }).fial(function(){
            $('#content-data').html('<p>Error</p>');
        });
    });
</script>

这是我的fetch.php

$query=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_array($query)){
    $subdata=array();
    $subdata[]=$row[0]; //id
    $subdata[]=$row[1]; //name
    $subdata[]=$row[2]; //salary
    $subdata[]=$row[3]; //age           //create event on click in button edit in cell datatable for display modal dialog           $row[0] is id in table on database
    $subdata[]='<button type="button" id="getEdit" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal" data-id="'.$row[0].'"><i class="glyphicon glyphicon-pencil">&nbsp;</i>Edit</button>
                <button type="button" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-trash">&nbsp;</i>Delete</button>';
    $data[]=$subdata;
}

这是我的editdata.php

if(isset($_REQUEST['id'])){
    $id=intval($_REQUEST['id']);
    $sql="select * from pcfields_data WHERE pcfield_id=$id";
    $run_sql=mysqli_query($con,$sql);
    while($row=mysqli_fetch_array($run_sql)){
        $per_id=$row[0];
        $per_name=$row[1];
        $per_salay=$row[2];
        $per_age=$row[3];
    }

2 个答案:

答案 0 :(得分:1)

index.php文件,其中包含所有数据列表和弹出菜单:

    <!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<?php 
include_once('connection.php');

$sql = "SELECT id, firstname, lastname FROM users";
$result = $conn->query($sql); ?>


    <table id="table_id" class="display">
        <thead>
            <tr>
                <th>id</th>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            if ($result->num_rows > 0) { 
            while($row = $result->fetch_assoc()) {
            ?>
                <tr>
                    <td><?php echo $row["id"]; ?></td>
                    <td><?php echo $row["firstname"]; ?></td>
                    <td><?php echo $row["lastname"]; ?></td>
                    <td><a class="btn btn-info btn-lg" data-toggle="modal" data-target="#Modal<?php echo $row["id"]; ?>">edit</a></td>
                </tr>

                <!-- model -->

                    <div class="modal fade" id="Modal<?php echo $row['id']; ?>" role="dialog">
                        <div class="modal-dialog">

                          <!-- Modal content-->
                          <div class="modal-content">
                            <div class="modal-header">
                              <button type="button" class="close" data-dismiss="modal">&times;</button>
                              <h4 class="modal-title">poup id = <?php echo $row["id"]; ?></h4>
                            </div>
                            <div class="modal-body">

                              <form action="/testphp/php.php" method="post" id="updateform">
                                <div>
                                    <label for="name">Firstname:</label>
                                    <input type="text" name="firstname" id="name" value="<?php echo $row["firstname"]; ?>"  />
                                </div>
                                <div>
                                    <label for="name">Lastname:</label>
                                    <input type="text" name="lastname" id="name" value="<?php echo $row["lastname"]; ?>"  />
                                </div>
                                <input type="hidden" name="id" value="<?php echo $row["id"]; ?>">
                                <div>
                                    <input type="submit" value="update" />
                                </div>
                              </form>

                            </div>
                            <div class="modal-footer">
                              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            </div>
                          </div>

                        </div>
                    </div>

                <!-- model -->

            <?php } } else { ?>
                <tr>
                    <td><?php echo "0 results"; ?></td>
                </tr>
            <?php 
            }
            $conn->close();
            ?>
        </tbody>
    </table>

    <script type="text/javascript">
        $(document).ready( function () {
            $('#table_id').DataTable();
        });


        $("#updateform").submit(function(e) {

            var form = $(this);
            var url = form.attr('action');

            $.ajax({
                   type: "POST",
                   url: url,
                   data: form.serialize(), // serializes the form's elements.
                   success: function(data)
                   {
                        if(data == 1){
                            location.reload();
                            console.log(data); // show response from the php script.
                        }
                   }
                 });

            e.preventDefault(); // avoid to execute the actual submit of the form.
        });
    </script>
</body>
</html>

php.php文件包含更新数据:

<?php
error_reporting(0);

include_once('connection.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $id = $_POST['id'];

    $sql = "UPDATE users SET firstname='".$firstname."',lastname='".$lastname."' WHERE id=".$id;

    if ($conn->query($sql) === TRUE) {
        echo true;
    } else {
        echo "Error updating record: " . $conn->error;
    }

    $conn->close();
}

connection.php数据库连接文件如下所示:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testphp";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?> 

testphp.sql mysql数据库:

-- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Oct 29, 2018 at 06:15 AM
-- Server version: 5.7.21
-- PHP Version: 7.2.4

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `testphp`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) NOT NULL,
  `fullname` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `firstname`, `lastname`, `fullname`) VALUES
(1, 'test11333ss', 'test111', 'test1'),
(2, 'test211', 'test2dsafd', 'test2');
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

答案 1 :(得分:1)

您需要为操作按钮使用类名而不是ID,因为ID应该是唯一的。

我将使用btn-primary作为编辑按钮的类名,并以btn-danger作为删除按钮的类名的例子。

解决方案是将单击事件处理程序附加到“编辑”按钮和任何表单元格上,并使用stopPropagation()函数防止事件传播。

// Handle click on "Edit" button or any table cell
$('#example').on('click', 'tbody .btn-primary, tbody td', function(e){
   // Prevent event propagation
   e.stopPropagation();

   var $row = $(this).closest('tr');
   var data = table.row($row).data();

   alert('Edit ' + data[0]);
});

// Handle click on "Delete" button
$('#example').on('click', 'tbody .btn-danger', function(e){
   // Prevent event propagation
   e.stopPropagation();

   var $row = $(this).closest('tr');
   var data = table.row($row).data();

   alert('Delete ' + data[0]);
});

有关代码和演示,请参见this example