I have 2 pages html and php. where a table is selected based on which option then a table and a script for that table is loaded. When adding the script in an php echo response. I get( Undefined variable $btn in) only after adding the 3rd section im assuming it has something to do with the response or the ways its inserted. Can anyone tell me what wrong? or guide me? chatgpt dont know, ur my last hope…
Why does the code stop working and error out after adding the 3rd section of code?
Once the code is working i will secure it with pdo and prepared statements lets focus on the question
// This function is user to insert data in database
$('#btnSaveAction').on('click', function () {
params = ''
$('td[contentEditable="true"]').each(function () {
if ($(this).text() != '') {
if (params != '') {
params += '&';
}
params += $(this).data('id') + '=' + $(this).text();
}
});
if (params != '') {
alert(params);// santize data
$.ajax({
url: 'function.php',
type: 'POST',
data: params,
success: function (response) {
$('#ajax-response').append(response);
$('td[contentEditable="true"]').text('');
}
});
return false;
}
});
// This function is used for edit the row to make it editable
$('#tbl').on('click', '.edit', function () {
$('#tbl').find('.save, .cancel').hide();
$('#tbl').find('.edit').show();
$(this).hide().siblings('.save, .cancel').show();
$(this).closest('td').siblings().each(
function () {
var inp = $(this).find('input');
if (inp.length) {
$(this).text(inp.val());
} else {
var t = $(this).text();
$(this).attr('contentEditable', 'true');
}
});
});
// This function is used for edit the row to make it editable
$('#tbl').on('click', '.cancel', function () {
$('#tbl').find('.save, .cancel').hide();
$(this).hide().siblings('.edit').show();
$(this).closest('td').siblings().each(
function () {
$(this).attr('contentEditable', 'false');
location.reload();
});
});
and once u add this its starts to error but it all looks correct
// This function is used for saving the edit data in database
$('#tbl').on('click', '.save', function () {
var $btn = $(this);
$('#tbl').find('.save, .cancel').hide();
$btn.hide().siblings('.edit').show();
params = '';
var id = $btn.data('id');
$(this).closest('td').siblings().each(function () {
$(this).attr('contentEditable', 'false');
if (params != '') {
params += '&';
}
params += $(this).data('id') + '=' + $(this).text();
});
params += '&id' + '=' + id;
alert(params);// santize data
if (params != '') {
$.ajax({
url: 'function.php',
type: 'POST',
data: params,
success: function (response) {
$('#ajax-response').append(response);
// $('td[contentEditable='true']').text('');
}
});
return false;
}
});
// this ajax is using for deleting the row
$('#tbl').on('click', '.del', function () {
var el = this;
var deleteid = $(this).data('id');
console.log(deleteid);
var confirmalert = confirm('Are you sure?');
if (confirmalert == true) {
$.ajax({
url: 'function.php',
type: 'POST',
data: {
id: deleteid,
action: 'del'
},
success: function (response) {
if (response == 1) {
// Remove row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
} else {
alert('Invalid ID.');
}
}
});
}
});
i have tried these
// using this
$("#ajax-response").append(response);
//but can also use this
var maincontent = document.getElementById("ajax-response");
maincontent.innerHTML = response;
//or this
$.getScript('asset/custom.js'); // Execute the JavaScript file
this dont work either ,neither does placing it before or after the html
$('script', response).each(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = this.innerHTML;
document.body.appendChild(script);
html
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manager combined Console</title>
<link rel="stylesheet" href="asset/style11.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
#btnSaveAction {
display: inline-block;
color: #444;
border: 1px solid #CCC;
background: #DDD;
box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.2);
cursor: pointer;
vertical-align: middle;
max-width: 100px;
padding: 5px;
text-align: center;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
// Load table data when a table is selected
$(document).on('change', '#tableSelect', function() {
var table = $(this).val();
if (table) {
$.ajax({
url: 'function77.php',
type: 'GET',
data: { table: table },
success: function(response) {
// Replace the current content with the new response
$("#tableData").html(response);
$('script', response).each(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = this.innerHTML;
document.body.appendChild(script);
});
}
});
} else {
$('#tableData').html('');
}
});
</script>
</head>
<body>
<h1>Business Console</h1>
<!-- Dropdown to select table -->
<select id="tableSelect">
<option value="">Select Business</option>
<option value="maploc">Business Manager</option>
<option value="reviews">1-Location1</option>
<option value="table3">2-Location2</option>
<option value="table4">3-Location3</option>
<option value="table5">4-Location4</option>
<option value="table6">5-Location5</option>
<option value="table7">6-Location6</option>
<option value="table8">7-Location7</option>
<option value="table9">8-Location8</option>
<option value="table10">9-Location9</option>
<option value="table11">10-Location10</option>
</select>
<div id="tableData">
<!-- Table data will be inserted here dynamically -->
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</body>
</html>
and the function77.php
<?php
require_once "dbcontroller555.php";
// Initialize DBController instance
$db_handle = new DBController();
// Function to validate and clean input data
function cleanInput($data) {
// Trim whitespaces and sanitize input to prevent XSS
return htmlspecialchars(trim($data));
}
// Check if table is selected via GET request
if (isset($_GET['table'])) {
$table = $_GET['table'];
try {
// Fetch rows from the selected table
$sql = "SELECT * FROM $table ORDER BY CAST(id AS UNSIGNED) DESC";
$stmt = $db_handle->getConnection()->prepare($sql);
$stmt->execute();
$productResult = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Check if any rows are returned
if (!empty($productResult)) {
echo "
<script>
// This function is user to insert data in database
$('#btnSaveAction').on('click', function () {
params = ''
$('td[contentEditable="true"]').each(function () {
if ($(this).text() != '') {
if (params != '') {
params += '&';
}
params += $(this).data('id') + '=' + $(this).text();
}
});
if (params != '') {
alert(params);// santize data
$.ajax({
url: 'function.php',
type: 'POST',
data: params,
success: function (response) {
$('#ajax-response').append(response);
$('td[contentEditable="true"]').text('');
}
});
return false;
}
});
// This function is used for edit the row to make it editable
$('#tbl').on('click', '.edit', function () {
$('#tbl').find('.save, .cancel').hide();
$('#tbl').find('.edit').show();
$(this).hide().siblings('.save, .cancel').show();
$(this).closest('td').siblings().each(
function () {
var inp = $(this).find('input');
if (inp.length) {
$(this).text(inp.val());
} else {
var t = $(this).text();
$(this).attr('contentEditable', 'true');
}
});
});
// This function is used for edit the row to make it editable
$('#tbl').on('click', '.cancel', function () {
$('#tbl').find('.save, .cancel').hide();
$(this).hide().siblings('.edit').show();
$(this).closest('td').siblings().each(
function () {
$(this).attr('contentEditable', 'false');
location.reload();
});
});
// This function is used for saving the edit data in database
$('#tbl').on('click', '.save', function () {
var $btn = $(this);
$('#tbl').find('.save, .cancel').hide();
$btn.hide().siblings('.edit').show();
params = '';
var id = $btn.data('id');
$(this).closest('td').siblings().each(function () {
$(this).attr('contentEditable', 'false');
if (params != '') {
params += '&';
}
params += $(this).data('id') + '=' + $(this).text();
});
params += '&id' + '=' + id;
alert(params);// santize data
if (params != '') {
$.ajax({
url: 'function.php',
type: 'POST',
data: params,
success: function (response) {
$('#ajax-response').append(response);
// $('td[contentEditable='true']').text('');
}
});
return false;
}
});
// this ajax is using for deleting the row
$('#tbl').on('click', '.del', function () {
var el = this;
var deleteid = $(this).data('id');
console.log(deleteid);
var confirmalert = confirm('Are you sure?');
if (confirmalert == true) {
$.ajax({
url: 'function.php',
type: 'POST',
data: {
id: deleteid,
action: 'del'
},
success: function (response) {
if (response == 1) {
// Remove row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
} else {
alert('Invalid ID.');
}
}
});
}
});
</script>
<script src='https://code.jquery.com/jquery-1.10.2.js'></script>
<div class='container'>
<div id='add-product'>
<div class='txt-heading'>Add Location</div>
<p id='statusMessage' style='color: green; display: none;'></p>
<table cellpadding='10' cellspacing='1' border='1'>
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Manager</strong></th>
<th><strong>Address</strong></th>
<th><strong>Phone</strong></th>
<th><strong>Fax</strong></th>
<th><strong>Hours</strong></th>
</tr>
<tr>
<td contentEditable='true' data-id='Name'></td>
<td contentEditable='true' data-id='Manager'></td>
<td contentEditable='true' data-id='Address'></td>
<td contentEditable='true' data-id='Telephone' style='text-align:right;'></td>
<td contentEditable='true' data-id='Fax'></td>
<td contentEditable='true' data-id='Hours' style='text-align:right;'></td>
</tr>
</tbody>
</table>
<br>
<div id='btnSaveAction'>Insert</div>
</div>
<br>
<div id='list-product'>
<div class='txt-heading'>Products</div>
<table id='tbl' cellpadding='10' cellspacing='1' border='1'>
<tbody id='ajax-response'>
<tr>
<th><strong>Name</strong></th>
<th><strong>Manager</strong></th>
<th><strong>Address</strong></th>
<th><strong>Phone</strong></th>
<th><strong>Fax</strong></th>
<th><strong>Hours</strong></th>
<th><strong>Actions</strong></th>
</tr>
";
foreach ($productResult as $row) {
echo "<tr>
<td data-id='Name'>" . htmlspecialchars($row['Name']) . "</td>
<td data-id='Manager'>" . htmlspecialchars($row['Manager']) . "</td>
<td data-id='Address'>" . htmlspecialchars($row['Address']) . "</td>
<td data-id='Telephone'>" . htmlspecialchars($row['Telephone']) . "</td>
<td data-id='Fax'>" . htmlspecialchars($row['Fax']) . "</td>
<td data-id='Hours'>" . htmlspecialchars($row['Hours']) . "</td>
<td>
<button class='edit btn btn-success'><i class='fa fa-pencil' aria-hidden='true'></i></button>
<button type='button' id='edit' class='save btn btn-success' data-id='" . htmlspecialchars($row['id']) . "'
style='display: none'><i class='fa fa-check' aria-hidden='true'></i></button>
<button type='button' id='edit' class='cancel btn btn-danger' style='display: none'><i class='fa fa-times'
aria-hidden='true'></i></button>
<button class='del btn btn-warning' data-id='" . htmlspecialchars($row['id']) . "'><i class='fa fa-trash'
aria-hidden='true'></i></button>
</td>
</tr>";
}
echo "
</tbody>
</table>
</div>
</div>
";
} else {
echo "No data found in this table.";
}
} catch (PDOException $e) {
echo "Error fetching data: " . $e->getMessage();
}
if (isset($_POST['Name'])) {
$id = "";
$Name = "";
$Manager = "";
$Address = "";
$Telephone = "";
$Fax = "";
$Hours = "";
if (!empty($_POST["id"])) {
$id = $db_handle->cleanData($_POST["id"]);
}
if (!empty($_POST["Name"])) {
$Name = $db_handle->cleanData($_POST["Name"]);
}
if (!empty($_POST["Manager"])) {
$Manager = $db_handle->cleanData($_POST["Manager"]);
}
if (!empty($_POST["Address"])) {
$Address = $db_handle->cleanData($_POST["Address"]);
}
if (!empty($_POST["Telephone"])) {
$Telephone = $db_handle->cleanData($_POST["Telephone"]);
}
if (!empty($_POST["Fax"])) {
$Fax = $db_handle->cleanData($_POST["Fax"]);
}
if (!empty($_POST["Hours"])) {
$Hours = $db_handle->cleanData($_POST["Hours"]);
}
if (isset($_POST['id'])) {
$sql = "UPDATE
maploc
SET
Name = '$Name',
Manager = '$Manager',
Address = '$Address',
Telephone = '$Telephone',
Fax = '$Fax',
Hours = '$Hours'
WHERE
maploc.id = $id";
} else {
$sql = "INSERT INTO
maploc (Name,Manager,Address,Telephone,Fax,Hours)
VALUES ('" . $Name . "','" . $Manager . "','" . $Address . "','" . $Telephone . "','" . $Fax . "','" . $Hours . "')";
}
$id = $db_handle->executeInsert($sql);
if (!empty($id)) {
$sql = "SELECT * FROM maploc ORDER BY CAST(id AS UNSIGNED) DESC";
$productResult = $db_handle->readData($sql);
}
?>
<?php
if (!empty($productResult)) {
?>
<tr>
<td data-id="Name"><?php echo $productResult[0]["Name"]; ?></td>
<td data-id="Manager"><?php echo $productResult[0]["Manager"]; ?></td>
<td data-id="Address"><?php echo $productResult[0]["Address"]; ?></td>
<td data-id="Telephone"><?php echo $productResult[0]["Telephone"]; ?></td>
<td data-id="Fax"><?php echo $productResult[0]["Fax"]; ?></td>
<td data-id="Hours"><?php echo $productResult[0]["Hours"]; ?></td>
<td>
<button class="edit btn btn-success"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<button type="button" id="edit" class="save btn btn-success" data-id="<?php echo $productResult[0]["id"]; ?>"
style="display: none"><i class="fa fa-check" aria-hidden="true"></i></button>
<button type="button" id="edit" class="cancel btn btn-danger" style="display: none"><i class="fa fa-times"
aria-hidden="true"></i></button>
<button class="del btn btn-warning" data-id="<?php echo $productResult[0]["id"]; ?>"><i class="fa fa-trash"
aria-hidden="true"></i></button>
</td>
</tr>
<?php
}
}
//echo '<script>';
//echo 'console.log("it ran");';
//echo '</script>';
?>
<?php
$id = 0;
if (isset($_POST['action']) == 'del') {
$id = $db_handle->cleanData($_POST["id"]);
}
if ($id > 0) {
// Check record exists
$sql = "SELECT * from maploc WHERE id = '$id' ";
$productResult = $db_handle->readData($sql);
if ($productResult > 0) {
// Delete record
$query = "DELETE FROM maploc WHERE id=" . $productResult[0]['id'];
$db_handle->executeInsert($query);
echo 1;
exit;
} else {
echo 0;
exit;
}
}
}//isset(GET['table']
//if ($_SERVER['REQUEST_METHOD'] === 'POST') {
?>