How can I develop an alert system like Facebook's, where User A add User B, User B will get some number in Friend Request Section on the header like in the image below. How can I develop something like that?
How can we get numbers like this??how can i get codes in PHP and JQuery?
I presume you want a means of alerting user A, when user B 'friends' him/her without requiring a page refresh?
This requires "AJAX". AJAX stands for Asynchronous Javascript and XML, but this is an overloaded term now-a-days with the actual exchange data structure often using JSON instead of XML. JSON is JavaScript Object Notation. Anyway, the idea is that your webpage--without being refreshed--can make periodic calls to your server to get new or updated information to update the display with. With PHP and jQuery, you'll want to first set up the AJAX call on your page like this:
$(function() { // on document ready
function updateAlerts() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
// Update the DOM to show the new alerts!
if (response.friendRequests > 0) {
// update the number in the DOM and make sure it is visible...
$('#unreadFriendRequestsNum').show().text(response.friendRequests);
}
else {
// Hide the number, since there are no pending friend requests
$('#unreadFriendRequestsNum').hide();
}
// Do something similar for unreadMessages, if required...
}
});
setTimeout('updateAlerts()', 15000); // Every 15 seconds.
}
});
This will, every 15 seconds, make a request to your server at the url /check.php on the same domain as the origin of the webpage. The PHP should query your database and and return the number of unread friend requests. Perhaps something like this:
<?php
function isValid(session) {
// given the user's session object, ensure it is valid
// and that there's no funny business
// TO BE IMPLEMENTED
}
function sanitize(input) {
// return CLEAN input
// TO BE IMPLEMENTED
}
// Be sure to check that your user's session is valid before proceeding,
// we don't want people checking other people's friend requests!
if (!isValid(session)) { exit; }
$method = sanitize($_POST['method']);
switch ($method) {
case 'checkAlerts' :
// Check DB for number of unread friend requests and or unread messages
// TO BE IMPLEMENTED
$response = ['friendRequests' => $num_friend_requests,
'messages' => $num_unread_messages ];
return json_encode( $response );
exit;
case 'someOtherMethodIfRequired' :
// ...
exit;
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With