I am creating an editable row in HTML, PHP and java script.
This is the html and php element in index.php :
<tbody id="inforTypeTable">
<?php foreach ($inforTypes as $room) : ?>
<tr data-id="<?= $room['id'] ?>">
<td><?= $room['id'] ?></td>
<td contenteditable="true" class="room-type"><?= htmlspecialchars($room['room_type']) ?></td>
<td contenteditable="true" class="room-desc"><?= htmlspecialchars($room['room_desc']) ?></td>
<td>
<i class="bi bi-floppy2-fill save-btn" title="Save" style="cursor:pointer; opacity:0.5;"></i>
<i class="bi bi-trash3-fill delete-btn" title="Delete" style="cursor:pointer;"></i>
</td>
</tr>
<?php endforeach; ?>
</tbody>
and the following is the script to handle the save-btn (I included the update and delete too):
$(document).ready(function() {
$('[data-bs-toggle="tooltip"]').tooltip();
$('td[contenteditable="true"]').on('input', function() {
$(this).closest('tr').find('.save-btn').css('opacity', '1').css('cursor', 'pointer');
});
// Save changes
$(document).on("click", ".save-btn", function() {
let row = $(this).closest("tr");
let id = row.data("id");
let roomType = row.find(".room-type").text().trim();
let roomDesc = row.find(".room-desc").text().trim();
console.log("Saving:", roomType, roomDesc);
$.post("rooms.functions.php", {
action: id ? "update" : "add",
id,
roomType,
roomDesc
}, function(response) {
console.log("Raw Response:", response); // Log the raw response
// Only parse the response if it's valid JSON
try {
let res = JSON.parse(response);
alert(res.message);
if (res.status === "success" && !id) {
row.attr("data-id", res.id);
row.find("td:first").text(res.id);
}
} catch (e) {
console.error("JSON Parse Error---> ", e);
alert("Error processing request. Please check the console for details.");
}
});
});
// Delete room type
$(document).on("click", ".delete-btn", function() {
let row = $(this).closest("tr");
let id = row.data("id");
if (confirm("Are you sure you want to delete this room type?")) {
$.post("rooms.functions.php", {
action: "delete",
id
}, function(response) {
console.log("Raw Response (Delete):", response);
try {
let res = JSON.parse(response);
alert(res.message);
if (res.status === "success") {
row.remove();
}
} catch (e) {
console.error("JSON Parse Error:", e);
alert("Error processing request. Check console for details.");
}
});
}
});
// Add new row
$("#addNew").click(function() {
let newRow = $(`
<tr>
<td>New</td>
<td contenteditable="true" class="room-type"></td>
<td contenteditable="true" class="room-desc"></td>
<td>
<i class="bi bi-floppy2-fill save-btn" title="Save" style="cursor:pointer; opacity:0.5;"></i>
<i class="bi bi-trash3-fill delete-btn" title="Delete" style="cursor:pointer;"></i>
</td>
</tr>
`);
$("#roomTypeTable").append(newRow);
});
});
The following is the php which manages the crud:
<?php
require '../config.php'; // Database connection
header('Content-Type: application/json'); // Force JSON response
ob_clean(); // Remove any unwanted whitespace or characters before output
ob_start(); // Start output buffering
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'update') {
$id = $_POST['id'] ?? null;
$roomType = trim($_POST['roomType'] ?? '');
$roomDesc = trim($_POST['roomDesc'] ?? '');
if (!empty($id) && !empty($roomType) && !empty($roomDesc)) {
$stmt = $pdo->prepare("UPDATE room_type SET room_type = ?, room_desc = ?, created_date = NOW(), created_by = 'WIAL' WHERE id = ?");
$stmt->execute([$roomType, $roomDesc, $id]);
echo json_encode(["status" => "success", "message" => "Room type updated successfully!"]);
} else {
echo json_encode(["status" => "error", "message" => "Invalid data for update."]);
}
} elseif ($action === 'delete') {
$id = $_POST['id'] ?? null;
if (!empty($id)) {
$stmt = $pdo->prepare("DELETE FROM room_type WHERE id = ?");
$stmt->execute([$id]);
echo json_encode(["status" => "success", "message" => "Room type deleted successfully!"]);
} else {
echo json_encode(["status" => "error", "message" => "Invalid ID for delete."]);
}
} elseif ($action === 'add') {
$roomType = trim($_POST['roomType'] ?? '');
$roomDesc = trim($_POST['roomDesc'] ?? '');
if (!empty($roomType) && !empty($roomDesc)) {
$stmt = $pdo->prepare("INSERT INTO room_type (room_type, room_desc, created_date, created_by) VALUES (?, ?, NOW(), 'WIAL')");
$stmt->execute([$roomType, $roomDesc]);
$lastId = $pdo->lastInsertId(); // Get last inserted ID
echo json_encode(["status" => "success", "message" => "Room type added successfully!", "id" => $lastId]);
} else {
echo json_encode(["status" => "error", "message" => "Invalid data for add."]);
}
} else {
echo json_encode(["status" => "error", "message" => "Invalid action."]);
}
ob_end_flush(); // Send output buffer
exit; // Ensure PHP stops execution after sending JSON
}
Add, update and delete is managed successfully, means the table in database is updated.
however the page is not updated/refreshed. and there is error
Raw Response (Delete):
Object { status: "success", message: "Room type deleted successfully!" }
rooms.php:322:33
JSON Parse Error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
<anonymous> https://localhost/dev/index.php:324
jQuery 7
<anonymous> https://localhost/dev/index.php:318
jQuery 8
<anonymous> https://localhost/dev/index.php:280
jQuery 13
index.php:330:37
<anonymous> https://localhost/dev/index.php:330
jQuery 7
<anonymous> https://localhost/dev/index.php:318
jQuery 8
<anonymous> https://localhost/dev/index.php:280
jQuery 13
Can you advise how to have the table in index.php refreshed once the operation is successfully executed?