Jump to content

Olumide

Members
  • Posts

    112
  • Joined

  • Last visited

  • Days Won

    3

Olumide last won the day on November 25 2023

Olumide had the most liked content!

Profile Information

Recent Profile Visitors

1,720 profile views

Olumide's Achievements

Advanced Member

Advanced Member (4/5)

10

Reputation

5

Community Answers

  1. I have an admission application form, and I want an email and SMS notification to be sent to the applicant's email and phone upon successful registration. I have tried using the mail() function, but I am not receiving any email notifications at the recipient's email. I also tried using Gmail, but none of them are working. I used Composer to install the vendor autoload, but it is still not working. I don't know where the error is coming from. Below are the tables and the code: Table CREATE TABLE applicants ( id INT AUTO_INCREMENT PRIMARY KEY, application_id VARCHAR(20) UNIQUE, surname VARCHAR(100), othername VARCHAR(100), dob DATE, phone VARCHAR(20), email VARCHAR(100), lga VARCHAR(100), state_origin VARCHAR(100), current_school VARCHAR(100), current_class VARCHAR(50), proposed_class ENUM('Year 7 (JSS1)', 'Year 8 (JSS2)', 'Year 10 (SS1)', 'Year 11 (SS2)', 'Year 1 (PRY 1)', 'Year 2 (PRY 2)', 'Year 3 (PRY 3)', 'Year 4 (PRY 4)'), status VARCHAR(20) DEFAULT 'Pending' ); CREATE TABLE exam_dates ( id INT AUTO_INCREMENT PRIMARY KEY, exam_date DATE, type ENUM('Online', 'On-site'), is_past BOOLEAN DEFAULT FALSE ); CREATE TABLE exam_registrations ( id INT AUTO_INCREMENT PRIMARY KEY, applicant_id INT, exam_date_id INT, FOREIGN KEY (applicant_id) REFERENCES applicants(id), FOREIGN KEY (exam_date_id) REFERENCES exam_dates(id) ); ALTER TABLE applicants ADD registered_on DATETIME; PHP <?php session_start(); require_once('db_config.php'); //require_once(__DIR__ . '/../vendor/autoload.php'); require_once('vendor/autoload.php'); // Import PHPMailer classes into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // Fetch available exam dates from the database try { $stmt = $pdo->query("SELECT * FROM exam_dates WHERE is_past = FALSE"); $exam_dates = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Check if the user is logged in as an applicant if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'applicant') { header("Location: login.php"); exit(); } // Logout logic if (isset($_POST['logout'])) { session_destroy(); // Destroy all session data header("Location: login.php"); // Redirect to the login page exit(); } // Set the applicant_id from the applicants table try { $username = $_SESSION['username']; $stmt = $pdo->prepare("SELECT * FROM applicants WHERE application_id = ?"); $stmt->execute([$username]); $applicant = $stmt->fetch(PDO::FETCH_ASSOC); $_SESSION['applicant_id'] = $applicant['id']; $applicant_email = $applicant['email']; // Store the applicant's email address } catch(PDOException $e) { echo "Error: " . $e->getMessage(); exit(); } // Check if the applicant has already registered for an exam date try { $stmt = $pdo->prepare("SELECT * FROM exam_registrations WHERE applicant_id = ?"); $stmt->execute([$applicant['id']]); $registered_exam_dates = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Handle exam registration if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['exam_date'])) { // Check if the applicant has already registered for an exam date if (!empty($registered_exam_dates)) { //echo "You have already registered for an exam date."; exit(); } $applicant_id = $_SESSION['applicant_id']; $exam_date_id = $_POST['exam_date']; // Insert exam registration details into exam_registrations table try { $stmt = $pdo->prepare("INSERT INTO exam_registrations (applicant_id, exam_date_id) VALUES (?, ?)"); $stmt->execute([$applicant_id, $exam_date_id]); // Redirect to exam confirmation page or show success message header("Location: exam_confirmation.php"); // Send SMS to applicant $message = "Thank you for your application. Your username is: " . $applicant['application_id'] . " and Password is your surname."; $api_url = 'my api url'; $token = 'my token'; $sender = 'Olu'; $recipient = $applicant['phone']; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => array( 'token' => $token, 'sender' => $sender, 'to' => $recipient, 'message' => $message, ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo 'cURL Error #:' . $err; } else { echo 'SMS sent successfully.'; } // Send email notification to applicant using PHPMailer sendEmailNotification($applicant_email, $applicant['application_id'], $applicant['surname']); exit(); } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } } // Function to send email notification using PHPMailer function sendEmailNotification($recipientEmail, $applicationId, $surname) { // Instantiate PHPMailer $mail = new PHPMailer(true); try { // SMTP configuration (Gmail) $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'olu@gmail.com'; $mail->Password = 'mypassword'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; // Email content $mail->setFrom('olu@gmail.com', 'My Schol'); $mail->addAddress($recipientEmail); $mail->Subject = 'Application Registration Confirmation'; $mail->isHTML(true); $mail->Body = "Dear $surname,<br><br>Thank you for your application at my Schol. Your username is: $applicationId and Password is your surname.<br><br>Best regards,<br>My Schol"; // Send email $mail->send(); echo 'Email sent successfully!'; } catch (Exception $e) { echo "Error: {$mail->ErrorInfo}"; } } ?> <!DOCTYPE html> <html> <head> <title>Applicant Dashboard</title> <script> // JavaScript function to display a popup function displayPopup() { alert("You have already registered for an exam date."); } </script> </head> <body> <h2>Welcome, <?php echo $applicant['surname']; ?></h2> <!-- Display applicant information --> <p>Applicant's Name: <?php echo $applicant['surname'] . ' ' . $applicant['othername']; ?></p> <p>Application ID: <?php echo $applicant['application_id']; ?></p> <p>Date of Birth: <?php echo $applicant['dob']; ?></p> <p>Phone: <?php echo $applicant['phone']; ?></p> <p>Email: <?php echo $applicant['email']; ?></p> <p>Local Government Area: <?php echo $applicant['lga']; ?></p> <p>State of Origin: <?php echo $applicant['state_origin']; ?></p> <p>Current School: <?php echo $applicant['current_school']; ?></p> <p>Current Class: <?php echo $applicant['current_class']; ?></p> <p>Proposed Class: <?php echo $applicant['proposed_class']; ?></p> <!-- Selected exam date --> <p>Selected Exam Date: <?php if (!empty($registered_exam_dates)) { $selected_exam_date_id = $registered_exam_dates[0]['exam_date_id']; foreach ($exam_dates as $date) { if ($date['id'] == $selected_exam_date_id) { echo date('F j, Y', strtotime($date['exam_date'])) . " (" . $date['type'] . ")"; break; } } } else { echo 'Not selected'; } ?> </p> <hr> <!-- Exam date selection --> <h3>Exam Date Selection</h3> <form id="exam_form" method="post"> <label for="exam_date">Select Exam Date:</label><br> <select id="exam_date" name="exam_date"> <?php foreach ($exam_dates as $date) : ?> <option value="<?php echo $date['id']; ?>"><?php echo $date['exam_date'] . " (" . $date['type'] . ")"; ?></option> <?php endforeach; ?> </select><br><br> <input type="button" value="Register for Exam" onclick="checkExamRegistration()"> <!--<input type="submit" value="Register for Exam">--> </form> <!-- Application status --> <h3>Application Status</h3> <p>Status: <?php echo $applicant['status']; ?></p> <!-- Logout form --> <form method="post"> <input type="submit" name="logout" value="Logout"> </form> <script> // Function to check if the applicant has already registered function checkExamRegistration() { <?php if (!empty($registered_exam_dates)): ?> displayPopup(); <?php else: ?> document.getElementById("exam_form").submit(); <?php endif; ?> } </script> </body> </html>
  2. I understand your point, for instance storing names again in the invoice table when the names are available in the student table is like exhausting more spaces and I don't think it can last if the storage space is not much, it can crash. You and @Barand have contributed tremendously. I am not yet an expert like you all, but I believe in consistent practicing.
  3. The fee is not constant, it do change, and for instance, a student who lives in hostel (Boarder) might decide he want to be coming from home as Day student, and a Day student can even decide he want to stay in hostel for a week maybe for a purpose known to him, and this do cause confusion if there is fixed price. Also, some parents might decide they want to pay less on any of the fee either IGCSE, Sports or anything. That is why I think entering the fee manually could be okay to handle such scenario. Some students are on scholarship where tuition will be free, but they will pay for other expenses and some on free feeding, and so on. And School fee may change anytime.
  4. Thanks @BarandCan you please give me more hints on this?
  5. total_fee_payable is still not calculating well but calculated_total_fee calculated well as required. I want this calculated as: total_fee_payable = (fee_amount + total_fee_from_items) - (total_fee_from_items + discount_amount) I have tried many approach but not working, it is not adding the amounts in the items_table to the total_fee_payable in the invoices table. From the sample query below: From items_table: invoice_id 118 should be added to the invoices id total_fee_payable CREATE TABLE `invoices` ( `id` int(11) NOT NULL, `student_id` int(11) NOT NULL, `semester_id` int(11) NOT NULL, `student_name` varchar(255) NOT NULL, `current_class_id` varchar(255) DEFAULT NULL, `fee_description` varchar(255) NOT NULL, `fee_amount` decimal(10,2) NOT NULL, `less_fee_description` varchar(255) DEFAULT NULL, `less_fee_amount` decimal(10,2) DEFAULT NULL, `discount_amount` decimal(10,2) DEFAULT NULL, `total_fee_payable` decimal(10,2) NOT NULL, `invoice_number` varchar(50) NOT NULL, `status` enum('PAID','PENDING') DEFAULT 'PENDING', `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -- Dumping data for table `invoices` -- INSERT INTO `invoices` (`id`, `student_id`, `semester_id`, `student_name`, `current_class_id`, `fee_description`, `fee_amount`, `less_fee_description`, `less_fee_amount`, `discount_amount`, `total_fee_payable`, `invoice_number`, `status`, `created_at`, `updated_at`) VALUES (118, 678, 16, 'AU', 'Year 11', 'school fee ', '50000.00', 'hg', '1000.00', '1000.00', '48000.00', 'B/2024/67982', 'PENDING', '2024-02-03 00:12:06', '2024-02-03 00:12:06'); -- -- Triggers `invoices` -- DELIMITER $$ CREATE TRIGGER `calculate_total_fee_payable_update` BEFORE UPDATE ON `invoices` FOR EACH ROW BEGIN SET NEW.total_fee_payable = ( SELECT COALESCE(SUM(fee_amount), 0) FROM items_table WHERE invoice_id = NEW.id ) + NEW.fee_amount - COALESCE((NEW.less_fee_amount + NEW.discount_amount), 0); END $$ DELIMITER ; ALTER TABLE `invoices` ADD PRIMARY KEY (`id`), ADD KEY `semester_id` (`semester_id`), ADD KEY `fk_invoices_student` (`student_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `invoices` -- ALTER TABLE `invoices` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=119; -- -- Constraints for dumped tables -- -- -- Constraints for table `invoices` -- ALTER TABLE `invoices` ADD CONSTRAINT `fk_invoices_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`), ADD CONSTRAINT `invoices_ibfk_1` FOREIGN KEY (`semester_id`) REFERENCES `semester` (`id`); COMMIT; CREATE TABLE `items_table` ( `id` int(11) NOT NULL, `invoice_id` int(11) NOT NULL, `fee_description` varchar(255) NOT NULL, `fee_amount` decimal(10,2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; INSERT INTO `items_table` (`id`, `invoice_id`, `fee_description`, `fee_amount`) VALUES (16, 118, 'sports', '5000.00'), (17, 118, 'club', '5000.00'); ALTER TABLE `items_table` ADD PRIMARY KEY (`id`), ADD KEY `fk_items_invoice` (`invoice_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `items_table` -- ALTER TABLE `items_table` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- Constraints for dumped tables -- -- -- Constraints for table `items_table` -- ALTER TABLE `items_table` ADD CONSTRAINT `fk_items_invoice` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`); COMMIT;
  6. I realized my mistake. You elders are all amazing. I don't know which one I should marked as solutions but you all did very excellent and expedite my problem to be solved. However, I am still working on it as this is just a section and when I am finally done with this, I have a vital question to ask on PHP as someone told me when I went for an interview that in the next two years, PHP will be outdated and not sellable in the market again. error_reporting(E_ALL); ini_set('display_errors', 1); // Check if the form data is set if ( isset($_POST['semesterId']) && isset($_POST['studentName']) && isset($_POST['feeDescription']) && isset($_POST['feeAmount']) && isset($_POST['lessFeeDescription']) && isset($_POST['lessFeeAmount']) && isset($_POST['discountAmount']) && isset($_POST['invoiceNumber']) //I think the problem is adding the grandTotal variable here ) { // Get form data $semesterId = $_POST['semesterId']; $studentName = $_POST['studentName']; $feeDescription = $_POST['feeDescription']; $feeAmount = $_POST['feeAmount']; $lessFeeDescription = $_POST['lessFeeDescription']; $lessFeeAmount = $_POST['lessFeeAmount']; $discountAmount = $_POST['discountAmount']; $invoiceNumber = $_POST['invoiceNumber']; // Calculate grand total $grandTotal = $feeAmount - ($lessFeeAmount + $discountAmount); // Additional validation if (empty($_POST['studentName']) || empty($_POST['feeDescription']) || empty($_POST['feeAmount'])) { header('HTTP/1.1 400 Bad Request'); echo 'Invalid form data. Please fill out all required fields.'; exit; } try { $query = "INSERT INTO invoices (semester_id, student_name, fee_description, fee_amount, less_fee_description, less_fee_amount, discount_amount, invoice_number, total_fee_payable) VALUES (:semesterId, :studentName, :feeDescription, :feeAmount, :lessFeeDescription, :lessFeeAmount, :discountAmount, :invoiceNumber, :totalFeePayable)"; // Prepare the query $stmt = $pdo->prepare($query); // Bind parameters $stmt->bindParam(':semesterId', $semesterId, PDO::PARAM_INT); $stmt->bindParam(':studentName', $studentName, PDO::PARAM_STR); $stmt->bindParam(':feeDescription', $feeDescription, PDO::PARAM_STR); $stmt->bindParam(':feeAmount', $feeAmount, PDO::PARAM_STR); $stmt->bindParam(':lessFeeDescription', $lessFeeDescription, PDO::PARAM_STR); $stmt->bindParam(':lessFeeAmount', $lessFeeAmount, PDO::PARAM_STR); $stmt->bindParam(':discountAmount', $discountAmount, PDO::PARAM_STR); $stmt->bindParam(':invoiceNumber', $invoiceNumber, PDO::PARAM_STR); $stmt->bindParam(':totalFeePayable', $grandTotal, PDO::PARAM_STR); // Bind grandTotal to the total_fee_payable column
  7. I am on it right now, could you believe I only modified the save_invoice.php script and got working, but I have removed all the calculations in javascript and still not working until now, but I want to retrace my steps again. You guys (no, I won't call you guys, but elders) are amazing and wonderful family. I am still on it, and will surely be here when there is hurdles again. Thanks for now.
  8. Hmmm, this is very deep, I am not an expert in programming but learn everyday. The script work fine before not until I wanted to be inserting the grandTotal under fee_total_payable. And I have comment out the grandTotal again from all my code but still stopped working. From the console network tab, attached is the picture
  9. I have this html form which worked, but I added grandTotal to populate its column "total_fee_payable" in the table. When I added this, I altered the javascript and php code to insert the data into the database. Suddenly, it stopped working and when I checked the console log, it shows data saved successfully. What could be the problem please? Here is part of my html form <div id="student-details" class="w3-margin-top w3-margin-bottom"> <h2>Student Details</h2> <!-- Custom label and input container --> <div class="w3-row-padding"> <div class="w3-half w3-padding"> <label for="student-name">Name:</label> <input type="text" id="student-name" name="studentName" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="current-class">Current Class:</label> <input type="text" id="current-class" name="currentClass" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="selected-semester">Selected Semester:</label> <input type="text" id="selected-semester" name="selectedSemester" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="invoice-number">Invoice Number:</label> <input type="text" id="invoice-number" name="invoiceNumber" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="item">Fee Description:</label> <input type="text" id="item" name="feeDescription" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="price">Amount:</label> <input type="number" id="price" name="feeAmount" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="lessFee">Enter Less Fee Description:</label> <input type="text" id="fee_description" name="less_fee_description" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="priceAmount">Amount:</label> <input type="number" id="fee_amount" name="less_fee_amount" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="price">Discount Amount:</label> <input type="number" id="discount_amount" name="discount_amount" class="w3-input w3-border" autocomplete="off"> </div> </div> </div> <h2 class="w3-margin-bottom">Analysis</h2> <div class="w3-responsive"> <table class="w3-table w3-hoverable w3-bordered w3-striped" id="order-item-tbl"> <tfoot> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Sub-Total</th> <th class="bg-transparent w3-border w3-right-align" id="subTotalText">0</th> </tr> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Grand Total</th> <th class="bg-transparent w3-border w3-right-align" id="grandTotal" name="grandTotal">0</th> </tr> </tfoot> </table> </div><br> <button type="button" id="order-form-submit" class="w3-button w3-blue w3-block"><i class="far fa-plus-square"> </i> Add Invoice</button> </div> Here is the javascript // Function to update the grand total based on the formula function updateGrandTotal() { // Get values from the form var price = parseFloat(document.getElementById('price').value) || 0; var feeAmount = parseFloat(document.getElementById('fee_amount').value) || 0; var discountAmount = parseFloat(document.getElementById('discount_amount').value) || 0; // Calculate grand total var grandTotal = price - (feeAmount + discountAmount); // Update the grand total element document.getElementById('grandTotal').textContent = grandTotal.toFixed(2); } // Attach the update function to input events document.getElementById('price').addEventListener('input', updateGrandTotal); document.getElementById('fee_amount').addEventListener('input', updateGrandTotal); document.getElementById('discount_amount').addEventListener('input', updateGrandTotal); // Function to save invoice data function saveInvoiceData() { var semesterId = $('#semester').val(); var studentName = $('#student-name').val(); var feeDescription = $('#item').val(); var feeAmount = $('#price').val(); var lessFeeDescription = $('#fee_description').val(); var lessFeeAmount = $('#fee_amount').val(); var discountAmount = $('#discount_amount').val(); //var grandTotal = $('#grandTotal').val(); var invoiceNumber = $('#invoice-number').val(); // Make an AJAX request to save invoice data $.ajax({ url: 'invoice.php', method: 'POST', data: { semesterId: semesterId, studentName: studentName, feeDescription: feeDescription, feeAmount: feeAmount, lessFeeDescription: lessFeeDescription, lessFeeAmount: lessFeeAmount, discountAmount: discountAmount, //grandTotal: grandTotal, invoiceNumber: invoiceNumber }, success: function (response) { // Handle success response if needed console.log('Invoice data saved successfully.'); }, error: function (error) { console.error('Error:', error); } }); } // Bind the function to "Save" button $('#order-form-submit').on('click', function () { saveInvoiceData(); }); }); Here is the invoice.php // Check if the form data is set if ( isset($_POST['semesterId']) && isset($_POST['studentName']) && isset($_POST['feeDescription']) && isset($_POST['feeAmount']) && isset($_POST['lessFeeDescription']) && isset($_POST['lessFeeAmount']) && isset($_POST['discountAmount'])&& //isset($_POST['grandTotal'])&& isset($_POST['invoiceNumber']) ) { // Get form data $semesterId = $_POST['semesterId']; $studentName = $_POST['studentName']; $feeDescription = $_POST['feeDescription']; $feeAmount = $_POST['feeAmount']; $lessFeeDescription = $_POST['lessFeeDescription']; $lessFeeAmount = $_POST['lessFeeAmount']; $discountAmount = $_POST['discountAmount']; //$grandTotal = floatval($_POST['grandTotal']); $invoiceNumber = $_POST['invoiceNumber']; // Additional validation if (empty($_POST['studentName']) || empty($_POST['feeDescription']) || empty($_POST['feeAmount'])) { header('HTTP/1.1 400 Bad Request'); echo 'Invalid form data. Please fill out all required fields.'; exit; } try { $query = "INSERT INTO invos (semester_id, student_name, fee_description, fee_amount, less_fee_description, less_fee_amount, discount_amount, invoice_number) VALUES (:semesterId, :studentName, :feeDescription, :feeAmount, :lessFeeDescription, :lessFeeAmount, :discountAmount, :invoiceNumber)"; // Prepare the query $stmt = $pdo->prepare($query); // Bind parameters $stmt->bindParam(':semesterId', $semesterId, PDO::PARAM_INT); $stmt->bindParam(':studentName', $studentName, PDO::PARAM_STR); $stmt->bindParam(':feeDescription', $feeDescription, PDO::PARAM_STR); $stmt->bindParam(':feeAmount', $feeAmount, PDO::PARAM_STR); $stmt->bindParam(':lessFeeDescription', $lessFeeDescription, PDO::PARAM_STR); $stmt->bindParam(':lessFeeAmount', $lessFeeAmount, PDO::PARAM_STR); $stmt->bindParam(':discountAmount', $discountAmount, PDO::PARAM_STR); //$stmt->bindParam(':grandTotal', $grandTotal, PDO::PARAM_STR); $stmt->bindParam(':invoiceNumber', $invoiceNumber, PDO::PARAM_STR); try { // ... // Output the executed query for debugging echo $stmt->queryString; // Execute the query $stmt->execute(); $rowCount = $stmt->rowCount(); if ($rowCount > 0) { echo 'Invoice data saved successfully.'; } else { echo 'No rows affected. Check for errors.'; } } catch (PDOException $e) { // Handle database errors echo 'Error: ' . $e->getMessage(); }
  10. Thank you @Barand I modified my html form and my Javascript to triggered the calculations in real time as I type. Now, it is time for me to bind my parameters.
  11. After using the debugger by add console log, I still don't noticed where the issue is. And you also please tell me the anomalies in my html div tags? $(document).ready(function () { const orderItemTbl = $('#order-item-tbl'); const addOrderBtn = $('#add-order-btn'); const lessTotalText = $('#lessTotal'); const subTotalText = $('#subTotalText'); let totalLessAmount = 0; let totalPriceForFeeDescriptions = 0; $(addOrderBtn).click(function (e) { e.preventDefault(); addItem(); }); function addItem() { var item = $('#item').val(); var price = $('#price').val(); var less = $('#less').val(); var lessAmount = $('#less_amount').val(); // Validate input fields if (item === '' || price === '' || price < 1) { return false; } price = parseFloat(price).toFixed(2); // two decimal places var tr = createRow(item, price); // Check if less and lessAmount are provided if (less !== '' && lessAmount !== '') { var tr2 = createRow(less, lessAmount); orderItemTbl.find('tbody').append(tr, tr2); // Update total less amount totalLessAmount += parseFloat(lessAmount); console.log("totalLessAmount after adding:", totalLessAmount); } else { orderItemTbl.find('tbody').append(tr); // Update total price for fee descriptions totalPriceForFeeDescriptions += parseFloat(price); console.log("totalPriceForFeeDescriptions after adding:", totalPriceForFeeDescriptions); } orderItemTbl.find('tbody tr.noData').hide(); // Clear input fields after adding an item clearInputFields(); // Update subtotal updateSubTotal(); // Update total less amount updateTotalLessAmount(); } function createRow(description, amount) { var tr = $('<tr>'); var removeBtn = $('<button type="button" class="remove-item w3-button w3-red w3-round w3-tiny"><i class="fas fa-times"></i></button>'); tr.append('<td class="w3-center w3-border"></td>'); tr.append(`<td class="w3-border">${description}</td>`); tr.append(`<td class="w3-right-align w3-border numeric">${parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}</td>`); tr.find('td:first-child').append(removeBtn); removeBtn.click(function () { if (confirm('Are you sure to remove this item?')) { tr.remove(); clearInputFields(); if (orderItemTbl.find('tbody tr').length <= 1) { orderItemTbl.find('tbody tr.noData').show(); } if (amount !== '' && parseFloat(amount) > 0) { totalLessAmount -= parseFloat(amount); console.log("totalLessAmount after removing:", totalLessAmount); } updateSubTotal(); updateTotalLessAmount(); } }); return tr; } function clearInputFields() { $('#item').val(''); $('#price').val(''); $('#less').val(''); $('#less_amount').val(''); } function updateSubTotal() { var subTotal = totalPriceForFeeDescriptions - totalLessAmount; console.log("totalPriceForFeeDescriptions:", totalPriceForFeeDescriptions); console.log("totalLessAmount:", totalLessAmount); subTotalText.text(subTotal.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')); } function updateTotalLessAmount() { lessTotalText.text(totalLessAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')); } }); Attached picture
  12. It is not showing error in my browser console both on chrome and edge. I don't know why?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.