基于AJAX&PHP实现无刷新无点击通知实时更新的技术问询
Hey Tarek, great job getting the core notification system up and running! The issue right now is that your getNotif() function only runs once when the page finishes loading. To make notifications update automatically without any user action, we can implement periodic polling with JavaScript's setInterval—here's how to do it, plus some optimizations to keep things efficient:
1. Basic Auto-Refresh with setInterval
This is the simplest fix that works seamlessly with your existing code. We’ll tell the browser to run your getNotif() function on a regular interval (e.g., every 30 seconds).
Update your JavaScript file like this:
$(document).ready(function() { function getNotif(){ $.ajax({ type: "GET", url: "../phpOnly/getNotif.php", data: {getNotif: ""}, dataType:"json", success: function(data) { document.getElementById("insideNotif").innerHTML = data.notif; $(".unreadNotif").html(data.unread_notif); }, error: function() { // Optional: Handle failed requests (e.g., log a message for debugging) console.log("Oops, failed to fetch notifications."); } }); } // Run once when the page loads getNotif(); // Repeat every 30 seconds (adjust 30000 to change interval—30000ms = 30s) setInterval(getNotif, 30000); });
How it works:
setInterval(getNotif, 30000)schedules your AJAX function to run every 30 seconds. Tweak the interval based on how quickly you need notifications to update (avoid intervals shorter than 10 seconds to prevent overwhelming your server).
2. Optimize to Reduce Unnecessary Requests
To make this more efficient, we can only fetch new notifications instead of reloading the entire list every time. Here’s how to implement this:
Step 1: Modify JavaScript to track the last fetch time
$(document).ready(function() { // Store the time we last fetched notifications (start with current time) let lastFetchTime = new Date().toISOString(); function getNotif(){ $.ajax({ type: "GET", url: "../phpOnly/getNotif.php", data: { getNotif: "", lastFetch: lastFetchTime // Send last fetch time to PHP }, dataType:"json", success: function(data) { // Only update the DOM if there are new notifications if (data.notif !== "") { // Prepend new notifications to the top instead of replacing everything document.getElementById("insideNotif").innerHTML = data.notif + document.getElementById("insideNotif").innerHTML; } $(".unreadNotif").html(data.unread_notif); // Update the last fetch time to now lastFetchTime = new Date().toISOString(); } }); } getNotif(); setInterval(getNotif, 30000); });
Step 2: Update PHP to filter by the last fetch time
Modify your getNotif.php to use the lastFetch parameter and only return notifications created after that time:
<?php require("../include/dbconn.php"); session_start(); $uname=$_SESSION['uname']; $customerID=$_SESSION['customerID']; $notif=""; $unreadNotif=0; // Get the last fetch time from the request (default to a very old date if not set) $lastFetch = isset($_GET['lastFetch']) ? $_GET['lastFetch'] : '1970-01-01 00:00:00'; if(isset($_GET['getNotif'])){ // Updated query to only get notifications after the last fetch time $query = "SELECT notification_date,notification_status,products.product_id,product_title,product_picture,store_name,discount_percent FROM notification,products,stores,customer,favorite_list WHERE products.product_id=notification.product_id AND products.store_id=stores.store_id AND customer.customer_id=favorite_list.customer_id AND stores.store_id=favorite_list.store_id AND customer.customer_id='$customerID' AND product_active=1 AND notification_status!=-1 AND notification_date > '$lastFetch' // Filter for new notifications ORDER BY notification_date DESC"; $result = mysqli_query($db, $query); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_array($result)) { $notif_date=$row['notification_date']; $product_title=$row['product_title']; $product_picture=$row['product_picture']; $store_name=$row['store_name']; $discount_percent=$row['discount_percent']; $notif_status=$row['notification_status']; $notif.= "<li class=\"notification-box\"> <div class=\"row\"> <div class=\"col-lg-3 col-sm-3 col-3 text-center\"> <img src=\"../img/products/$product_picture\" class=\"\" style=\"width:80px;height:auto\"> </div> <div class=\"col-lg-8 col-sm-8 col-8\"> <strong class=\"text-info\">$store_name</strong> <div> Exclusive Now! $discount_percent% discount on $product_title </div> <small class=\"text-warning\">$notif_date</small> </div> </div> </li><hr>"; } // Keep your existing unread count query $query2 = "SELECT COUNT(notification_id) as unreadNotif FROM notification,products,stores,customer,favorite_list WHERE products.product_id=notification.product_id AND products.store_id=stores.store_id AND customer.customer_id=favorite_list.customer_id AND stores.store_id=favorite_list.store_id AND customer.customer_id='$customerID' AND product_active=1 AND notification_status=0 GROUP BY customer.customer_id"; $result2 = mysqli_query($db, $query2); $arr=mysqli_fetch_array($result2); $unreadNotif=$arr['unreadNotif']; } else{ // Don't show "No Notifications" if we're only checking for new ones—leave $notif empty $notif=""; } $data = array( 'notif' => $notif, 'unread_notif' => $unreadNotif ); echo json_encode($data); } else{ echo "error"; } ?>
Why this is better:
- Reduces server load by only fetching new notifications instead of the entire list every time.
- Avoids unnecessary DOM updates (only adds new notifications to the top instead of replacing everything).
3. Advanced: Real-Time Notifications with WebSockets
If you need instant notifications (instead of waiting for the next poll interval), you can use WebSockets. This lets your server push notifications to clients as soon as they’re created, instead of clients asking for updates.
For PHP, you can use libraries like Ratchet to set up a WebSocket server. Alternatively, if you’re open to adding Node.js to your stack, Socket.io is a popular choice. This requires more setup but gives you true real-time functionality.
内容的提问来源于stack exchange,提问作者Tarek AS

