Jump to content

Olumide

Members
  • Posts

    126
  • Joined

  • Last visited

  • Days Won

    3

Everything posted by Olumide

  1. 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.
  2. 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
  3. It is not showing error in my browser console both on chrome and edge. I don't know why?
  4. Hi, I am working on this script for invoice generation, from the image attached, is the input forms at left hand side, when the add order button is clicked, it add the fee description, amount, less fee description and amount less to the fee list as shown in the right hand side of the image. In the table in the right hand, Total less item(s) will sum all the amount less), sub-total will sum all the amount and subtract it from the total less. I still have to do discount and grandtotal but I had challenges with the sub-total, giving me the same value with the Total Less Amount. Please, the experts in the house who always rescue us from our downfall should please help me address this query. Here is the html form <div class="w3-half w3-padding"> <label for="item">Fee Description:</label> <input type="text" id="item" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="price">Amount:</label> <input type="number" id="price" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="less">Less Fee Description:</label> <input type="text" id="less" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="less_amount">Amount Less:</label> <input type="number" id="less_amount" class="w3-input w3-border" autocomplete="off"> </div> </div></div> <button type="button" id="add-order-btn" class="w3-button w3-blue w3-block"><i class="far fa-plus-square"> </i> Add Order</button> </div> <!-- Fee List Section --> <div class="w3-half w3-padding w3-form-container"> <h2 class="w3-margin-bottom">Fee List</h2> <div id="fee-list-content"> <!-- testing --> <div class="w3-card w3-round w3-margin card-body"> <div class="w3-container w3-padding"> <div class="w3-responsive"> <table class="w3-table w3-hoverable w3-bordered w3-striped" id="order-item-tbl"> <colgroup> <col width="5%"> <col width="70%"> <col width="20%"> </colgroup> <thead> <tr class="bg-gradient bg-dark-subtle"> <th class="bg-transparent w3-center w3-border"></th> <th class="bg-transparent w3-center w3-border">Fee Description</th> <th class="bg-transparent w3-center w3-border">Price</th> </tr> </thead> <tbody> <tr class="noData"> <th class="w3-center w3-border" colspan="3">No Item Listed Yet</th> </tr> </tbody> <tfoot> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Total Less Item(s)</th> <th class="bg-transparent w3-border w3-right-align" id="lessTotal">0</th> </tr> <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">Discount Amount</th> <th class="bg-transparent w3-border"> <input type="number" class="w3-input w3-small w3-round w3-right-align" step="any" name="discount_amount" id="discount_amount" min="0" max="1000000" value="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="grandTotalText">0</th> </tr> </tfoot> </table> Here is my javascript //<script> $(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); } else { orderItemTbl.find('tbody').append(tr); // Update total price for fee descriptions totalPriceForFeeDescriptions += parseFloat(price); } 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); } updateSubTotal(); updateTotalLessAmount(); } }); return tr; } function clearInputFields() { $('#item').val(''); $('#price').val(''); $('#less').val(''); $('#less_amount').val(''); } function updateSubTotal() { var subTotal = totalPriceForFeeDescriptions - 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, ',')); } });
  5. I checked but couldn't figured it out and I concatenate the firstname and lastname as full_name and modify it from the javascript but still not working.
  6. Oh! thanks, that was a mistake, I have corrected it and also modified the javascript but still getting this json error: Selected Year: 7 index.php:105 Current Semester: 2nd Term 2023/2024 index.php:136 Error fetching students: SyntaxError: Unexpected token '<', " <br /> <b>"... is not valid JSON Here is my modified javascript: <script> function updateStudentNames() { var selectedYear = document.getElementById("year").value; var currentSemester = document.getElementById("semester").value; // Get the current semester value console.log("Selected Year:", selectedYear); console.log("Current Semester:", currentSemester); var studentSelect = document.getElementById("student"); // Clear previous options studentSelect.innerHTML = ""; // Fetch and add new options based on the selected year and current semester if (selectedYear !== "") { fetch(`class_year.php?year=${selectedYear}&semester=${currentSemester}`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log("Fetched Data:", data); if (Array.isArray(data)) { data.forEach(student => { var option = document.createElement("option"); option.value = student.id; option.text = `${student.firstName} ${student.lastName}`; studentSelect.add(option); }); } else { console.error("Invalid data format. Expected an array."); } }) .catch(error => { console.error('Error fetching students:', error); }); } } </script>
  7. Thanks @Barand That solved the sql problem, but when I incorporated it, it is like I am having json issue, it is not being populated. Here is my class_year.php to populate the list... <?php include 'database.php'; $year = $_GET['year'] ?? null; if ($year === null) { http_response_code(400); echo json_encode(['error' => 'Missing required parameter: year']); exit(); } $sql = "SELECT s.id, s.firstname, s.lastname, c.classname FROM class c JOIN student_class sc ON sc.classid = c.id AND sc.semesterid = 1 JOIN student s ON sc.studentid = s.id WHERE c.year = ? ORDER BY s.lastname"; $stmt = getDatabaseConnection()->prepare($sql); $stmt->bind_param("i", $year); $stmt->execute(); $result = $stmt->get_result(); if (!$result) { http_response_code(500); // Internal Server Error echo json_encode(['error' => 'Database error']); exit(); } $students = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); getDatabaseConnection()->close(); // Set response headers to indicate JSON content header('Content-Type: application/json'); // Output JSON response echo json_encode($students); ?> And here is my json <script> function updateStudentNames() { var selectedYear = document.getElementById("year").value; console.log("Selected Year:", selectedYear); var studentSelect = document.getElementById("student"); // Clear previous options studentSelect.innerHTML = ""; // Fetch and add new options based on the selected year if (selectedYear !== "") { fetch(`class_year.php?year=${selectedYear}`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log("Fetched Data:", data); if (Array.isArray(data)) { data.forEach(student => { var option = document.createElement("option"); option.value = student.id; option.text = `${student.firstName} ${student.lastName}`; studentSelect.add(option); }); } else { console.error("Invalid data format. Expected an array."); } }) .catch(error => { console.error('Error fetching students:', error); }); } } </script> Html form <label for="semester" class="form-label">Current Session/Term</label> <input type="text" class="form-control rounded-0" name="semester" id="semester" required="required" value="<?= $current_term ?>" readonly> </div> <!-- test --> <label for="year" class="form-label">Year <select class="form-control rounded-0" name="year" id="year" required="required" onchange="updateStudentNames()"> <option value=''>- select year -</option> <option value='7'>Year 7</option> <option value='8'>Year 8</option> <option value='9'>Year 9</option> <option value='10'>Year 10</option> <option value='11'>Year 11</option> <option value='12'>Year 12</option> </select> </label> <label for="student" class="form-label">Student <select class="form-control rounded-0" name="student" id="student" required="required"> <!-- student name options for selected year will be dynamically populated here --> </select> </label>
  8. Wow! It run successfully on my workbench. You are good sir. Let me incorporate it into my script while I feed you back.
  9. Thank you @Barand Something like this attached image. When the year is selected, it fetch the students in that class.
  10. It is high time I tipped my cap to phpfreaks, small but mighty. Phpfreaks may be small in population, but the sense and knowledge derived from it are immeasurable. Here, you find gurus who are always ready to solve our problems. Since I joined this forum, I no longer bother flipping to any other place to get my problems solved because phpfreaks is competent. Please do not relent, and keep up the good work. Regards to you all.
  11. From the image attached, I have Session/Term not editable, it is the current session/term which is automatic. I have 5 classes and each class have like three or more arms such as 7A, 7B, 7C, 8A, 8B, 8C, etc In my html form for the Student class, I have Class 7, 8, etc which means 7A, 7B, 7C are under 7. I don't know how to go do it such that when Class is selected, it will populate the Student Name with the students in both arms of Class 7 (i.e all the students in 7A, 7B, 7C, etc). What I was using is to fetch all the names from the students table. Here is the html form: <label for="customer" class="form-label">Year <select class="form-control rounded-0" name="year" id="year" required="required"> <option value=''>- select year -</option> <option value='7'>Year 7</option> <option value='8'>Year 8</option> <option value='9'>Year 9</option> <option value='10'>Year 10</option> <option value='11'>Year 11</option> <option value='12'>Year 12</option> </select></label> </select> <label>Student <select class="form-control rounded-0" name="student" id="student" required="required"> <!-- student name options for selected year --> </select></label> Here are the tables -- Table structure for table `class` -- CREATE TABLE `class` ( `id` int(11) NOT NULL, `classname` varchar(45) DEFAULT NULL, `levelid` int(11) NOT NULL, `year` tinyint(4) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- Table structure for table `student_class` -- CREATE TABLE `student_class` ( `id` bigint(20) NOT NULL, `studentid` int(11) DEFAULT NULL, `semesterid` int(11) DEFAULT NULL, `classid` int(11) DEFAULT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- Table structure for table `student` -- CREATE TABLE `student` ( `id` int(11) NOT NULL, `firstName` varchar(50) NOT NULL, `lastName` varchar(50) NOT NULL, `otherName` varchar(50) NOT NULL, `matricNo` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `levelId` int(11) DEFAULT NULL, `DOB` date NOT NULL, `Phone` varchar(15) NOT NULL, `Email` varchar(100) NOT NULL, `image` varchar(255) DEFAULT NULL, `dateCreated` date NOT NULL, `leavingdate` date DEFAULT NULL, `login_disabled` tinyint(4) NOT NULL DEFAULT 0, `last_login` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  12. Thank you @Barand for your brilliant contribution and experienced contribution.
  13. Thank you @Barand I will run the query when I am on PC, currently on phone.
  14. Thanks for the clarification, but if I may ask, why is the graph not capturing the same class average in the result table and for the class average as you stated above, consider a situation whereby there are 20 students in a class and 16 out of the 20 students took Biology, will the class average still be total scores attained by all students divided by the number of students or divided by the number of students who took the subject? Thanks
  15. I guess this question should fits under PHP Coding Help.
  16. Thank you @Barand for the clarification. But now, I changed to Class Average, the Class Average I have in the Chart is different from the Class Average in the result table as shown in the attached images, and I used the same query used for the result class average for the chart too. SELECT s.subjectname, SUM(r.score) AS student_score, round(AVG(CASE r.exam WHEN 'Exam' THEN r.score * 100 / 70 ELSE r.score * 10 END), 2) AS mean FROM result r
  17. I want to generate a bar chart that will show the score of students in each subject and the mean. I am a bit confused in the mean aspect as what I am getting is far below my expected result. I would appreciate if more light can be shed on how to go about this getting the mean. I have the php code below and the output of the graph. $res = $pdo->prepare("SELECT s.subjectname, SUM(r.score) AS student_score, SUM(r.score) / COUNT(r.score) AS mean FROM result r JOIN student_class sc ON r.studentclassid = sc.id JOIN course c ON r.courseid = c.id JOIN subject s ON c.subjectid = s.id JOIN semester sm ON sc.semesterid = sm.id WHERE sm.id = ? AND sc.classid = ? AND sc.studentid = ? AND sm.semestername+0 <= 3 GROUP BY s.subjectname ORDER BY s.subjectname"); $res->execute([$semester, $clid, $student]); $data = $res->fetchAll(PDO::FETCH_ASSOC); // Prepare data for JSON response $response = [ 'labels' => [], 'scores' => [], 'classAvg' => [] ]; foreach ($data as $row) { $response['labels'][] = $row['subjectname']; $response['scores'][] = (int) $row['student_score']; $response['classAvg'][] = round((float) $row['mean'], 2); } // Return data in JSON format header('Content-Type: application/json'); echo json_encode($response); exit;
  18. Olumide

    Greetings!

    I assumed symfony does not support MySQL database.
  19. Olumide

    Greetings!

    Programming is good and funs but I am always baffled because there are many programming languages and more are still emerging. During my university days, I was only thought the basic QBasic, Fortran, MATLAB, C++, Assembly Language, Java, and Internet of a thing.
  20. Olumide

    Greetings!

    Please can you give me any link to learn the symfony in an easier mode as a beginner?
  21. A common approach is to use screen recording software to capture the animation and then convert it to the desired format.
  22. The problem might be with the placement of the array_unique function. Try this modification: $stmt = $pdo->prepare("SELECT DISTINCT terms FROM links WHERE terms LIKE ? GROUP BY terms"); $stmt->execute(array("$alpha%")); $data = $stmt->fetchAll(); foreach ($data as $result_tag) { $one = implode(', ', $result_tag) . ""; $two = strtok($one, ',') . "<br>"; $three = strtolower($two); $words = explode(" ", $three); $unique_words = array_unique($words); $string = implode(" ", $unique_words); echo $string; } exit();
  23. I use a different approach by using the `wp_get_referer()` function to check the referring page. If the referring page is not the 'order-received' page, then it will proceed with the redirection. ```php add_action('woocommerce_thankyou', 'upsell_redirect'); function upsell_redirect($order_id) { // Get the referring page $referer = wp_get_referer(); // Check if the referring page is not the 'order-received' page if ($referer && false === strpos($referer, 'order-received')) { WC()->session->set('original_order_id', $order_id); $upsell_page_url = home_url('/upsell-1'); wp_redirect($upsell_page_url); exit; } } ```
×
×
  • 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.