I have a page that has a table with 3 columns, two of which are data and the third has an edit button. When I click this button, the name is sent to a modal where it can be changed.
I need to do two things:
Update the name in the table and close the modal when click the Save Changes button on the modal.
Is it possible to do that?
Index.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--CSS Bootstrap-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- JS -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<table id="tabela">
<thead>
<th>#</th>
<th>Name</th>
<th></th>
</thead>
<tr>
<td>1</td>
<td class="name">Fred</td>
<td><button class="btnEdit">Edit</button></td>
</tr>
<tr>
<td>2</td>
<td class="name">Charles</td>
<td><button class="btnEdit">Edit</button></td>
</tr>
<tr>
<td>3</td>
<td class="name">John</td>
<td><button class="btnEdit">Edit</button></td>
</tr>
</table>
<div class="modal" id="modalTest" tabindex="-1" role="dialog">
<?php
include "modalTabela.php";
?>
</div>
<script>
//send name to php page
$(".btnEdit").click(function() {
var nome = $(this).closest('tr').find(".name").text();
$.ajax({
type: 'POST',
url: '//localhost/tabela/modalTabela.php',
data: {msg: nome },
}).done(function(data) {
//update html
$("#modalTest").html(data);
//show modal
$("#modalTest").modal("show");
});
});
</script>
</body>
</html>
modalTabela.php
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
$nome=$_POST['msg'];
echo "<label>Name</label><input type='text' id='edNome' value='$nome'></input>";
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnSalvar">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>