0

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?

  1. Given it doesn't need to be real time, is this the best approach?
  2. How can I improve the Ajax function to only append the status when there is a change of the column?
  3. 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));
}
?>
Community
  • 1
  • 1
z0mbieKale
  • 969
  • 1
  • 14
  • 44
  • 1
    Have you think about the web workers ? It can be a solution for what you want to do : [doc here](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) – Ugo T. Jul 09 '16 at 08:24
  • @UgoT. will look into it – z0mbieKale Jul 09 '16 at 08:41
  • A worker of some sort would definitely seem like the best option here. Sleeping the php process would (unless you spawn more of them) not work out well for multiple users - and not sleeping it would result in an insane amount of queries per minute. – CmdrSharp Jul 09 '16 at 08:44
  • @CmdrSharp what if I havde 1000 of users? – z0mbieKale Jul 09 '16 at 09:09
  • How about using a cronjob? – toesslab Jul 09 '16 at 09:20

1 Answers1

0

Long polling is good but not efficient for this scenario, as server will only know when to send notification. In long polling you will keep client and server both busy and will put load on server side with many user using long polling.

In the example given server will send notification as soon client completes all registration process, solution could be using server-side events.

Server-Sent Events:
In this type of connection client establishes persistent connection to server. Only server can send data to client. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is good protocol to be used instead of Long Polling.

Supported browsers: http://caniuse.com/#feat=eventsource

Alok Patel
  • 7,842
  • 5
  • 31
  • 47