![]() |
![]() |
You are not logged in. Please Login.
|
![]() |
|
---|---|
![]() ![]() Administrator Programming King
Posts: 95
Registered: 2013-12-25 |
_perp ├── components ├── database ├── js ├── php ├── index.php <--- also this file is in php dir └──index.html ![]() // index.php <?php // Any PHP code or includes can go here // For example, you might want to include a database connection or session start // include 'database_connection.php'; // session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Enhanced Complete Demo</title> <style> body { font-family: Arial, sans-serif; padding: 20px; } .outer-frame { border: 3px solid #444; border-radius: 15px; padding: 20px; max-width: 800px; margin: 0 auto; background-color: #f9f9f9; } .inner-frame { border: 1px solid #ccc; border-radius: 10px; padding: 20px; margin-top: 20px; background-color: white; } .input-group { margin-bottom: 15px; } label { display: inline-block; width: 100px; } input, textarea { width: 250px; padding: 5px; } textarea { vertical-align: top; } button { padding: 10px; margin-right: 10px; margin-top: 10px; } #dataGrid { margin-top: 20px; } </style> </head> <body> <div class="outer-frame"> <h1>Enhanced Complete Demo</h1> <div class="inner-frame"> <div class="input-group"> <label for="nameInput">Name:</label> <input type="text" id="nameInput" name="name" required> </div> <div class="input-group"> <label for="emailInput">Email:</label> <input type="email" id="emailInput" name="email" required> </div> <div class="input-group"> <label for="notesInput">Notes:</label> <textarea id="notesInput" name="notes" rows="4"></textarea> </div> <button id="submitBtn">Submit</button> <button id="refreshBtn">Refresh</button> <button id="clearCacheBtn">Clear Cache</button> </div> <div class="inner-frame"> <my-grid id="dataGrid"></my-grid> </div> </div> <script type="module" src="components/toast/toast.js"></script> <script type="module" src="components/grid/grid.js"></script> <script type="module" src="js/main.js"></script> </body> </html> ![]() // index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Enhanced Complete Demo</title> <style> body { font-family: Arial, sans-serif; padding: 20px; } .outer-frame { border: 3px solid #444; border-radius: 15px; padding: 20px; max-width: 800px; margin: 0 auto; background-color: #f9f9f9; } .inner-frame { border: 1px solid #ccc; border-radius: 10px; padding: 20px; margin-top: 20px; background-color: white; } .input-group { margin-bottom: 15px; } label { display: inline-block; width: 100px; } input, textarea { width: 250px; padding: 5px; } textarea { vertical-align: top; } button { padding: 10px; margin-right: 10px; margin-top: 10px; } #dataGrid { margin-top: 20px; } </style> </head> <body> <div class="outer-frame"> <h1>Enhanced Complete Demo</h1> <div class="inner-frame"> <div class="input-group"> <label for="nameInput">Name:</label> <input type="text" id="nameInput" name="name" required> </div> <div class="input-group"> <label for="emailInput">Email:</label> <input type="email" id="emailInput" name="email" required> </div> <div class="input-group"> <label for="notesInput">Notes:</label> <textarea id="notesInput" name="notes" rows="4"></textarea> </div> <button id="submitBtn">Submit</button> <button id="refreshBtn">Refresh</button> <button id="clearCacheBtn">Clear Cache</button> </div> <div class="inner-frame"> <my-grid id="dataGrid"></my-grid> </div> </div> <script type="module" src="components/toast/toast.js"></script> <script type="module" src="components/grid/grid.js"></script> <script type="module" src="js/main.js"></script> </body> </html> |
Last edited by: cgetty on Jan 31, 2025 11:15:13 pm
|
![]() |
|
---|---|
![]() ![]() Administrator Programming King
Posts: 95
Registered: 2013-12-25 |
_perp ├── components ![]() // grid class Grid extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); } connectedCallback() { this.render(); } render() { this.shadowRoot.innerHTML = ` <style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> <table> <thead> <tr> ${this.columns.map(col => `<th>${col}</th>`).join('')} </tr> </thead> <tbody> ${this.data.map(row => ` <tr> ${row.map(cell => `<td>${cell}</td>`).join('')} </tr> `).join('')} </tbody> </table> `; } set columns(value) { this._columns = value; this.render(); } get columns() { return this._columns || []; } set data(value) { this._data = value; this.render(); } get data() { return this._data || []; } } customElements.define('my-grid', Grid) ![]() // toast export class Toast { constructor(message, duration = 5000, type = 'info') { this.message = message; this.duration = duration; this.type = type; this.element = null; } show() { this.element = document.createElement('div'); this.element.className = `toast toast-${this.type}`; this.element.textContent = this.message; document.body.appendChild(this.element); setTimeout(() => this.element.classList.add('show'), 10); setTimeout(() => this.hide(), this.duration); } hide() { this.element.classList.remove('show'); setTimeout(() => this.element.remove(), 300); } } |
Last edited by: cgetty on Jan 31, 2025 11:17:57 pm
|
![]() |
|
---|---|
![]() ![]() Administrator Programming King
Posts: 95
Registered: 2013-12-25 |
├── database ![]() //table structure DB name is aiandme.db BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS "users" ( "rec_id" INTEGER, "username" TEXT NOT NULL, "email" TEXT UNIQUE, "created_at" DATETIME DEFAULT CURRENT_TIMESTAMP, "notes" TEXT, PRIMARY KEY("rec_id" AUTOINCREMENT) ); COMMIT; ![]() // sqlconnector.js const initSqlJs = require('sql.js'); async function initializeDatabase() { try { // Load SQL.js library const SQL = await initSqlJs(); // Create new database const db = new SQL.Database(); // Example: Create a simple table db.run(` CREATE TABLE users ( id INTEGER PRIMARY KEY, username TEXT, email TEXT ) `); return db; } catch (error) { console.error('Database initialization error:', error); } } module.exports = { initializeDatabase }; ![]() // test_connection.php <?php require_once 'db_connection.php'; echo " If you see this message without any errors, the database connection is working."; ?> ![]() // testdatabase.js const { initializeDatabase } = require('./sqlconnector'); async function testDatabaseConnection() { try { const db = await initializeDatabase(); // console.log("✓ Database successfully initialized"); // Optional: Test table creation const result = db.exec("PRAGMA table_info(users)"); console.log("Table structure:", result); } catch (error) { console.error("x Database initialization failed:", error); } } testDatabaseConnection(); |
Last edited by: cgetty on Jan 31, 2025 11:19:33 pm
|
![]() |
|
---|---|
![]() ![]() Administrator Programming King
Posts: 95
Registered: 2013-12-25 |
├── js ![]() // index.js import { Toast } from '../components/toast/toast.js'; << .. ? function loadRecords() { fetch('php/fetch_records.php') .then(response => response.json()) .then(records => { const tableBody = document.querySelector('#dataGrid tbody'); tableBody.innerHTML = ''; // Clear existing rows records.forEach(record => { const row = ` <tr> <td>${record.first_name}</td> <td>${record.last_name}</td> <td>${record.email}</td> <td>${record.notes}</td> </tr> `; tableBody.innerHTML += row; }); }) .catch(error => { console.error('Error:', error); new Toast('Error loading records', 5000, 'error').show(); }); } function validateForm() { var fields = ['firstName', 'lastName', 'email']; for (var i = 0; i < fields.length; i++) { if (document.getElementById(fields[i]).value.trim() === '') { return false; } } return true; } document.addEventListener('DOMContentLoaded', () => { loadRecords(); document.getElementById('submitBtn').addEventListener('click', function(event) { event.preventDefault(); if (!validateForm()) { new Toast('Please fill out all fields', 5000, 'error').show(); } else { // Handle form submission here new Toast('Form submitted successfully!', 5000, 'success').show(); // You might want to add code here to submit the form data } }); }); ![]() // File: main.js document.addEventListener('DOMContentLoaded', function() { console.log("DOM fully loaded"); const grid = document.getElementById('dataGrid'); if (grid) { console.log("Grid found"); grid.columns = ['Name', 'Email', 'Notes']; grid.data = [ ['John Doe', 'john@example.com', 'Initial entry'], ['Jane Smith', 'jane@example.com', 'Second entry'], ['Bob Johnson', 'bob@example.com', 'Third entry'] ]; } else { console.error("Grid not found"); } const submitBtn = document.getElementById('submitBtn'); console.log("Submit button:", submitBtn); if (submitBtn) { submitBtn.addEventListener('click', function(event) { console.log('Submit button clicked'); event.preventDefault(); const name = document.getElementById('nameInput').value.trim(); const email = document.getElementById('emailInput').value.trim(); const notes = document.getElementById('notesInput').value.trim(); console.log("Input values:", { name, email, notes }); if (!name || !email) { console.log("Validation failed"); // Error handling (toast to be implemented later) } else { console.log("Validation passed"); // Send data to the server fetch('php/save_data.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}¬es=${encodeURIComponent(notes)}` }) .then(response => response.text()) .then(text => { console.log('Raw server response:', text); return JSON.parse(text); }) .then(data => { if (data.status === 'success') { console.log('Data saved successfully'); // Update grid grid.data = [...grid.data, [name, email, notes]]; // Clear input fields document.getElementById('nameInput').value = ''; document.getElementById('emailInput').value = ''; document.getElementById('notesInput').value = ''; } else { console.error('Error saving data:', data.message); } }) .catch(error => { console.error('Error:', error); }); } }); } else { console.error("Submit button not found"); } const refreshBtn = document.getElementById('refreshBtn'); if (refreshBtn) { refreshBtn.addEventListener('click', function() { location.reload(); }); } const clearCacheBtn = document.getElementById('clearCacheBtn'); if (clearCacheBtn) { clearCacheBtn.addEventListener('click', function() { if (window.caches) { caches.keys().then(function(names) { for (let name of names) caches.delete(name); }); } location.reload(true); }); } }); |
Last edited by: cgetty on Jan 31, 2025 11:24:15 pm
|
![]() |
|
---|---|
![]() ![]() Administrator Programming King
Posts: 95
Registered: 2013-12-25 |
├── php ![]() // db_connection.php <?php try { // Use a full path to your SQLite database file $dbPath = $_SERVER['DOCUMENT_ROOT'] . "/ai/database/aiandme.db"; $pdo = new PDO("sqlite:" . $dbPath); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Uncomment the line below for debugging // echo 'Connected to the SQLite database successfully!'; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> ![]() // fetch_records.php <?php try { // Database connection (using PDO for SQLite) $pdo = new PDO("sqlite:" . "C:\xampp\htdocs\_my_project\database\aiandme.db"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // SQL query to select records $query = "SELECT first_name, last_name, email, notes FROM users"; // Prepare and execute the statement $stmt = $pdo->prepare($query); $stmt->execute(); // Fetch all records as associative array $records = $stmt->fetchAll(PDO::FETCH_ASSOC); // Return records as JSON for javascript processing echo json_encode($records); } catch(PDOException $e) { // Error handling echo json_encode(['error' => $e->getMessage()]); } ?> ![]() // save_data.php <?php // File: save_data.php // Database connection details $dbPath = __DIR__ . '/../database/aiandme.db'; // Adjust the path as needed // Set the content type to JSON header('Content-Type: application/json'); error_log("Attempting to save data"); try { $pdo = new PDO("sqlite:$dbPath"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Get the data from the POST request $name = $_POST['name'] ?? ''; $email = $_POST['email'] ?? ''; $notes = $_POST['notes'] ?? ''; // Prepare SQL and bind parameters $stmt = $pdo->prepare("INSERT INTO users (name, email, notes) VALUES (:name, :email, :notes)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); $stmt->bindParam(':notes', $notes); // Execute the prepared statement $stmt->execute(); error_log("Data saved successfully"); echo json_encode(['status' => 'success', 'message' => 'Data saved successfully']); } catch(PDOException $e) { error_log("Error saving data: " . $e->getMessage()); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); } ?> ![]() // submit.php <?php // Database connection $servername = "localhost"; // Change if necessary $username = "your_username"; // Your database username $password = "your_password"; // Your database password $dbname = "your_database"; // Your database name // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Get data from POST request $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; $email = $_POST['email']; $notes = $_POST['notes']; // Prepare and bind $stmt = $conn->prepare("INSERT INTO users (first_name, last_name, email, notes) VALUES (?, ?, ?, ?)"); $stmt->bind_param("ssss", $firstName, $lastName, $email, $notes); // Execute the statement if ($stmt->execute()) { echo json_encode(["success" => true]); } else { echo json_encode(["success" => false, "error" => $stmt->error]); } // Close connections $stmt->close(); $conn->close(); ?> ![]() // test_connection.php <?php require_once 'db_connection.php'; echo "If you see this message without any errors, the database connection is working.<br>"; // Add this new code to test a simple query try { $result = $pdo->query("SELECT 1"); if ($result !== false) { echo "Query executed successfully. Full database functionality confirmed."; } else { echo "Error executing query. Connection established but query failed."; } } catch(PDOException $e) { echo "Query error: " . $e->getMessage(); } ?> |