I know this has been asked, but I cannot figure it out. I am building a application, where user will receive notification (not real time, but close- so I don't want to use sockets).
The idea is following: if user signs up, his status is unverified. As soon as he completes the profile and the admins have approved, it will become verified and then I would like to display a little notification saying: "Hey, you are now verified!".
What I have tried
Been following this example.
So far I have tried polling and got stuck on the PHP side. In my logic I would need to loop the table and check for column changes. As soon as the column changes from 0 to 1, stop the loop and then append the data in the Ajax call. Is that correct?
- Given it doesn't need to be real time, is this the best approach?
- How can I improve the Ajax function to only append the status when there is a change of the column?
- In PHP, do I need to include a timestamp to check the data, and do I need
sleep()
?
JS
function addNotification(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
console.log(type + msg);
}
var notiCount = 0;
function vaitForNotification(){
/* This requests the url "notifications .php" When it complete (or errors)*/
$.ajax({
type: "GET",
url: "PHP/notifications.php",
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
if(data.verification_status[0].verification_status == "1"){
addNotification(data.verification_status[0].verification_status);
console.log("verified");
}else if(data.verification_status[0].verification_status == "0"){
addNotification(data.verification_status[0].verification_status);
console.log("not verified");
}
setTimeout(vaitForNotification, /* Request next message */
10000); /* ..after 10 seconds */
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addNotification("error", textStatus + " (" + errorThrown + ")");
setTimeout(vaitForNotification, /* Try again after.. */
15000); /* milliseconds (15seconds) */
}
});
};
vaitForNotification(); /* Start the inital request */
PHP
<?php
header('Content-type: application/json');
require_once '../../PHP/class.user.php';
$user_home = new USER();
if (empty($_SESSION['userSession'])) {
die();
}else{
$user_id= $_SESSION['userSession'];
$verification = $user_home->runQuery(
"SELECT verification_status FROM verification WHERE user_id =:user_id");
$verification->execute(array(":user_id"=>$user_id));
$verification_status = $verification->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array("verification_status" => $verification_status));
//sleep(rand(2,10));
}
?>