Pass Data from HTML Table to Modal and Then to PHP Script

Pass Data from HTML Table to Modal and then to PHP script

I added an attribute for each ‍button tag called record_id and the record ID should be stored in it.

for example :

<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="delBtn" record_id="1">
<span aria-hidden="true">×</span>
</button>

And when the button ('#delBtn') is clicked, I get the ID and save the variable.

 <script type="text/javascript">
var id = null
$('#delBtn').on('click', function() {
id=$("#delBtn").attr("record_id")
$('#deleteModal').show();
});

$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});

$('#accDelBtn').click(function() {

$.ajax({
type: "POST",
url: "delete.php",
data: { id: id }
})
});
</script>

And when I click on the button ('#accDelBtn'), I will send it.

Passing data from table to modal using PHP

You can use the below template.

Added people id in the view links so that the modal will know which particular record to retrieve.

Replace:

$str.= "<td ><a href='' data-toggle='modal'  data-target='#myModal'><i class='fa fa-eye'> VIEW RESUME</i></a></td> "; 

With:

$str.= "<td ><a href='' data-toggle='modal' data-people-id='".$people_id."' data-target='#myModal'><i class='fa fa-eye'> VIEW RESUME</i></a></td> "; 

On modal open, the below code retrieves the record from database using the people id that is in the view link. This uses ajax and a separate php file to retrieve the record of the relevant person.

Use this modal handler:

<script>   
$('#myModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var people_id = button.data('people-id');
var modal = $(this);

$.ajax({
type: "POST",
url: "get_person.php",
data: {
'people_id': people_id,
'submit': 'submit',
},
success: function(res) {
var response = JSON.parse(res);
var row = response.data;
if (response.status == "success") {
var full_name = row.FName + " " + row.MName + " " + row.LName;
$(modal).find('.modal-body').html('<label style="font-weight: bold;"><strong>Name: </strong>'+full_name+'</label></br>');
} else {
alert(response.msg);
}
}
});
});
</script>

The below code will respond with the requested record in json format to display in the modal.

Create a file named get_person.php

if(isset($_POST['submit'])){
$people_id = isset($_POST['people_id'])?$_POST['people_id']:0;

if($people_id > 0){
$dbh = new PDO('mysql:host=localhost;dbname=peeps', 'dbuser','dbpasss');
$stmt = $dbh->prepare("SELECT * FROM tblname WHERE people_id = :people_id");
$stmt->bindValue(":people_id", $people_id);

if($stmt->execute()){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
exit(json_encode(array('status'=>'success', 'data'=>$row)));
}
}
}

exit(json_encode(array('status'=>'fail', 'msg'=>'Failed to fetch data!')));

How to pass data from table of records to Modal for editing purposes

The best way to go about it , is to use events hooks which is tied to the modal to help manage dynamism on modals.

Take for example, you want to pass information from the for loop to the modal you can do this using just a modal and then update the modal as it opens.

check bootstrap docs you will see this hook for modal
show.bs.modal

we then use attributes from the button to pick out our information we are going to display on the modal, e.g

<button user-id="<?php echo $data[$i]->userID; ?>" first-name="<?php echo $data[$i]->firstname;?>">Edit</button>

then we can use Jquery to pick it up and hook it when the modal is opening

See for example code here, replace the static repeat with your dynamic coding

$('#myModal').on('show.bs.modal', function (e) {  // get information to update quickly to modal view as loading begins  var opener=e.relatedTarget;//this holds the element who called the modal      //we get details from attributes  var firstname=$(opener).attr('first-name');
//set what we got to our form $('#profileForm').find('[name="firstname"]').val(firstname); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript --><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


<table class="table"> <thead> <tr> <th>SN</th> <th>Firstname</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Theophilus</td> <td> <button class="btn btn-primary" first-name="Theophilus" data-toggle="modal" data-target="#myModal"> Edit </button> </td> </tr> <tr> <td>3</td> <td>Omoregbee</td> <td> <button class="btn btn-primary" first-name="Omoregbee" data-toggle="modal" data-target="#myModal"> Edit </button> </td> </tr> <tr> <td>3</td> <td>Endurance</td> <td> <button class="btn btn-primary" first-name="Endurance" data-toggle="modal" data-target="#myModal"> Edit </button> </td> </tr>
</tbody></table>
<!-- Modal --><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> <form id="profileForm"> Firstname : <input class="form-control" name="firstname" value="" placeholder="firstname"> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div></div>

Passing of data from main page to php query inside a modal

You need to use AJAX.

Ajax is a javascript methodology that allows you to exchange information with a back-end PHP file, just as you are attempting to do.

The AJAX code block will send data to the mymodal.php file, the mymodal.php file will do the MySQL lookup and create the HTML, then echo a string variable (which could be a json object or it could be the HTML that you built in your while loop) back to the main page. The AJAX code block will receive the data echo'd out from the PHP file inside the .done() function and, also in that function, you can modify the DOM to inject the new data. To the user, it will look like they clicked on an element with class edit and the data just appeared in the modal.

Note that you do not include the mymodal.php file in your main_file.php page, because the AJAX code block knows how to communicate with that file.

You will need to add the HTML structure for the modal to the bottom of your main page (note that it is initially set to display:none):

<style>
#lamodal{display:none;position:fixed;width:100vw;height:100vh;background:black;opacity:0.8;}
#mdl_inner{width:60%;height:40%;}
.myflex{display:flex;align-items:center;justify-content:center;}
</style>
<div id="lamodal" class="myflex">
<div id="mdl_inner"></div>
</div><!-- #lamodal -->

Your javascript (AJAX) will look something like this:

$(function(){
$("body").on('click', '.edit', function (e){
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'mymodal.php',
data: 'userid=id'
}).done(function(d){
//console.log('d: '+d);
$('#mdl_inner').html(d);
$('#lamodal').show();
});
});
});

Your mymodal.php file would be changed to look like this:

<?php 
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));

$out = '
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
';

while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
$out .= '
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
';
}

$out .= '
</tbody>
</table>
';

echo $out;
?>

Note how we are constructing a string variable and building it through concatination. When done, just echo $out and the newly-constructed HTML will appear in the .done() function of your AJAX code block.

See these additional AJAX examples and explanations:

http://www.jayblanchard.net/basics_of_jquery_ajax.html

Simple Like/Unlike text button - adding ajax etc

pass var to bootstrap modal where php will use this value

How to pass value from table to bootstrap modal to PHP?

This is not tested/debugged but refactor your code similar to this:

<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){

$out = '
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
';

while($row = mysqli_fetch_assoc($query_run)){
$out .= '<tr class="trID_' .$row['id']. '">';
$out .= '<td class="td_name">' . $row['name'] . '</td>';
$out .= '<td class="td_rollno">' . $row['rollno'] . '</td>';
$out .= '<td class="td_contact">' . $row['contact'] . '</td>';
$out .= '<td class="td_address">' . $row['address'] . '</td>';
$out .= "<td><button class='td_btn btn btn-link btn-custom dis'>EDIT</button> </td>";
$out .= '</tr>';
}
$out .= '</tbody></table>
echo $out;
?>

<script>
$(document).ready(){
$('.td_btn').click(function(){
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var name = $row.find('.td_name').val();
var rollno = $row.find('.td_rollno').val();
var contact = $row.find('.td_contact').val();
var address = $row.find('.td_address').val();
$('#frm_id').val(rowID);
$('#frm_name').text(name);
$('#frm_rollno').text(rollno);
$('#frm_contact').text(contact);
$('#frm_address').text(address);
$('#myModal').modal('show');
});
});//END document.ready
</script>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">

<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="frm_rollno">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>

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

</div>
</div>
</div>
<?php
}
}
?>

Notes:

(1) Create the entire table in a variable, then output the variable all at once.

(2) You only need one modal, not one modal for each table row. Therefore, remove modal creation from inside while loop.

(3) Use jQuery to:

   (a) detect button click in row

   (b) get table data for that row

   (c) populate fields in modal

   (d) display modal

You are using Bootstrap, which uses jQuery, so it makes sense to use jQuery to do this.

(4) Using jQuery to get values from table cells vs. input fields:

   (a) .text() - from table cells

   (b) .val() - from <input> or <textarea>


Here is a jsFiddle Demo you can play with that demonstrates how you can use jQuery to populate the modal depending on the row that was clicked.

passing parameter to modal window with data-target is not working

Multiple issues here.
First a </div> is missing at the end.


Then you are defining $groupdatalist in a foreach, but trying to use it outside the loop:

<div id="myModal-<?php echo $groupdatalist['gma_grp_id'];?>" class="modal show fade" data-backdrop="static">

If you want one modal per <td> you have to move your modal into the foreach loop.


Finally, you call the modal using $groupdatalist['gma_id']

 <span data-toggle="modal" data-target="#myModal-<?php echo $groupdatalist['gma_id'];?>">

but the modal ID is define using a different variable : $groupdatalist['gma_grp_id']:

<div id="myModal-<?php echo $groupdatalist['gma_grp_id'];?>"

Passing data-* to bootstrap Modal

  1. It is good to keep code more cleaner by using indent well.

  2. <script ~~> is also a tag like div , p , h1 but it has display : none. So of course you can add <script> tag in html file. It's OK.

  3. When Browser meet that <script src = "jquery.js">, the browser gets the jquery.js code from server ( in this case , your server ). So, You can't override other js code. It's just twice the work for the browser, and the jquery code is read twice.

  4. I can't understand what are you doing, specifically the <script type="text/javascript" src="/js/jquery-3.1.1.js"> code. You already included jquery-3.1.1.js above! Why are you doing that?

  5. Anyway, browser can not find #myModal in timing(or time?) that read the code $('#myModal').on('show.bs.modal', function (event) { ~~ . So the code should be under the model div.

Be Happy Coding ^^.



Related Topics



Leave a reply



Submit