Module 7: Live Data ඇතුළත් කිරීම (Live Data Insert)
පිටුව refresh නොකර, database එකට අලුත් දත්ත ඇතුළත් කරන form එකක් සහ Ajax ක්රියාවලියක් නිර්මාණය කරමු.
1. දත්ත ඇතුළත් කිරීමේ Interface එක (HTML Form)
පළමුව, පරිශීලකයාට නව දත්ත (නම සහ email) ඇතුළත් කිරීමට form එකක් සහ පවතින දත්ත පෙන්වීමට table එකක් සහිත සම්පූර්ණ interface එකක් නිර්මාණය කරමු.
ඔබගේ project folder එකේ, live-insert.html නමින් අලුත් file එකක් සාදා පහත HTML කේතය ඇතුලත් කරන්න.
<!DOCTYPE html>
<html lang="si">
<head>
<title>Live Data Insert</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-5">
<h1>Add New User</h1>
<p>Fill out the form below to add a new user to the database without page reload.</p>
<!-- Form for adding a new user -->
<form id="addUserForm">
<div class="row">
<div class="col-md-5 mb-3">
<input type="text" id="name" class="form-control" placeholder="Enter Name" required>
</div>
<div class="col-md-5 mb-3">
<input type="email" id="email" class="form-control" placeholder="Enter Email" required>
</div>
<div class="col-md-2 mb-3">
<button type="submit" class="btn btn-primary w-100">Add User</button>
</div>
</div>
</form>
<!-- Div to show success/error messages -->
<div id="messageDiv"></div>
<hr>
<h2>Existing Users</h2>
<!-- Div where the user table will be displayed -->
<div id="userTableDiv">Loading users...</div>
<script src="insert-script.js"></script>
</body>
</html>
2. දත්ත යැවීමට සහ පෙන්වීමට JavaScript
දැන්, insert-script.js නමින් අලුත් JavaScript file එකක් සාදා පහත කේතය ඇතුලත් කරන්න. මෙම script එකේ ප්රධාන කාර්යයන් දෙකක් ඇත:
- පිටුව load වූ විට පවතින users ලා පෙන්වීම.
- Form එක submit කල විට, දත්ත Ajax මගින් server එකට යැවීම.
document.addEventListener('DOMContentLoaded', function() {
const addUserForm = document.getElementById('addUserForm');
const messageDiv = document.getElementById('messageDiv');
const userTableDiv = document.getElementById('userTableDiv');
// --- Function to fetch and display users ---
function fetchUsers() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'fetch-data.php', true);
xhr.onload = function() {
if (this.status === 200) {
const users = JSON.parse(this.responseText);
let output = '<table class="table table-striped"><thead><tr><th>ID</th><th>Name</th><th>Email</th></tr></thead><tbody>';
users.forEach(function(user){
output += `<tr><td>${user.id}</td><td>${user.name}</td><td>${user.email}</td></tr>`;
});
output += '</tbody></table>';
userTableDiv.innerHTML = output;
}
}
xhr.send();
}
// --- Fetch users when the page loads ---
fetchUsers();
// --- Event listener for form submission ---
addUserForm.addEventListener('submit', function(e) {
e.preventDefault(); // Prevent the default form submission (page reload)
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const params = `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}`;
const xhr = new XMLHttpRequest();
// We use POST method to send data
xhr.open('POST', 'insert-data.php', true);
// This header is required for POST requests
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (this.status === 200) {
const response = JSON.parse(this.responseText);
messageDiv.innerHTML = `<div class="alert alert-${response.status}">${response.message}</div>`;
if (response.status === 'success') {
addUserForm.reset(); // Clear the form fields
fetchUsers(); // Refresh the user table to show the new entry
}
}
}
xhr.send(params);
});
});
3. දත්ත භාරගැනීමට PHP Backend එක
JavaScript වෙතින් POST method එකෙන් එවන දත්ත භාරගෙන, database එකට ඇතුලත් කර, සාර්ථකද අසාර්ථකද යන්න JSON response එකක් ලෙස නැවත යැවීමට අලුත් PHP file එකක් අවශ්යයි. insert-data.php නමින් අලුත් file එකක් සාදා පහත කේතය ඇතුලත් කරන්න.
<?php
require_once 'db.php'; // Include database connection
// Prepare a response object
$response = ['status' => 'error', 'message' => 'An error occurred.'];
// Check if it's a POST request and if name and email are set
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['name']) && !empty($_POST['email'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
// Basic validation
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
try {
// Prepare SQL to prevent SQL injection
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
// Execute the statement
if ($stmt->execute([$name, $email])) {
$response['status'] = 'success';
$response['message'] = 'User added successfully!';
} else {
$response['message'] = 'Failed to execute statement.';
}
} catch (PDOException $e) {
// Check for duplicate entry
if ($e->getCode() == 23000) {
$response['message'] = 'This email already exists.';
} else {
$response['message'] = 'Database error: ' . $e->getMessage();
}
}
} else {
$response['message'] = 'Invalid email format.';
}
} else {
$response['message'] = 'Invalid request or missing data.';
}
// Send the JSON response back to the JavaScript
header('Content-Type: application/json');
echo json_encode($response);
?>