smithrules
smithrules

Reputation: 15

How to show modal by clicking on the whole row instead of "Edit" button

I was able to get their corresponding ID from the array by adding attribute to my button, I was wondering if how can make popped up my modal by clicking whole table row instead of clicking the Edit button

My functional modal by clicking edit button:

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>

heres my 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;
}

heres my 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];
    }

Upvotes: 0

Views: 7349

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58860

You need to use class name for your action button instead of ID because ID should be unique.

I will use btn-primary as a class name for edit button and btn-danger as an example of class name for delete button.

The solution is to attach click event handler to both "Edit" button and any table cell and prevent event propagation by using stopPropagation() function.

// 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]);
});

See this example for code and demonstration.

Upvotes: 1

Hiren Siddhpura
Hiren Siddhpura

Reputation: 189

index.php file which contain all data list and popup mange:

    <!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 file witch contain update data:

<?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 database connection file goes like below:

<?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 database :

-- 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 */;

Upvotes: 1

Related Questions