How can i show notification per user with jquery and php? - javascript

I want show notification per user via API
for example if call api.php?user=1 via server or any admins, show alert to user1 if has any page, for example run alert('hi user 1');
or call api.php?user=2 via server or any admins, show alert to user2, for example run alert('hi user 2');
my solution is :
setInterval(function(){
$.get('ajax_responder.php',dataObj,function(){
});
},5000);
and in api.php saved request and in ajax_responder.php selected notification per user
but this solution not good,and reloaded per 5 second, i want better solution, when called api.php send request to user X
any have solution?!

There's no way the user can receive your notification if the user is not querying the server repeatedly. You can use a websocket to send/receive bi-directional

You can do that.
Step 1) When admin user type message store it in database. you can refer below as example.
TABLE NAME = USER_NOTIFICATION
==================================
USER_ID | IS_READ | MESSAGE
==================================
1 0 Hello User 1
-----------------------------------
2 0 Hello User 2
-----------------------------------
Step 2) Now from front side write Ajax call to keep checking on every minute or 5 minutes interval (Interval depends on server capability to handle the requests), whether for particular login user is having any unread message.
If you are using MySQL then you can use this below query to check unread notifications
SELECT `message` from USER_NOTIFICATION WHERE `user_id` = 1 and `is_read` = 0
now after getting result from above query show it in notification div (Remember create notification div with fixed position so it always popup)
Step 3) when user read admin message that time set is_read flag to 1, so next time that same message will not appear to user
Hope it will help you :)

Related

Active code for login user by time in asp.net core?

I want a code to be sent to the user and that code can be used for 3 minutes to log in the user so that the user cannot request a code in these 3 minutes.
David's advice is very good, you should write the code first and ask questions when you encounter problems.
Regarding your needs, I can provide you with some ideas.
First you need to know that when the browser client connects with the asp.net core webserver, the session ID is generated when the connection is established.
We can customize the code, codeState in session, to determine whether the user who established the connection has logged in.
code string type: 0123 or Az02
codeState null -> not generated
-1 -> expired
0 -> generated but un-use
1 -> used
if(codeState=null){
code = generate_code();
HttpContext.Session.SetString("code",code);
}
if(codeState == -1){
msg = "The code has expired, pls click the button to generate a new code";
}
if(codeState== 0){
msg = "The code has generated";
code = HttpContext.Session.GetString("code");
}
if(codeState== 1){
msg = "The code has used";
}

How to create multiple timer based on the timestamp of a data in database or delay the popup of the data base on the timestamp or time

Here I have shopping cart website and when a user check out it will go to the database name checkout. Then the admin will check the details of the user items then click accepted and it will go to db name pending payment. it will then notify the user that 4 hrs from now please pay using any credit card or else it will be deleted. I got a column name timer in my pending payment db which is a timestamp and another column name time which will get the date and time data . Im only doing this type of payment because I still don't know how to create a paypal payment so Im just checking my balance as a way of verification it will be temporary and also to have more choices wether it can be done using timestamp or date in php code like H/h/y/s something like that. Now if a user sends in a data then a timestamp appears in the database or (3/11/2019 5:03pm) for the time . Which will I fetch like this
$sql="SELECT * FROM pendingpayment;";
$sttmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($sttmt,$sql)){
echo "sql statement failed in displayitems.php line 71";
}else{
mysqli_stmt_execute($sttmt);
$ressult=mysqli_stmt_get_result($sttmt);
if(mysqli_num_rows($ressult)>0){
while($rowz=mysqli_fetch_assoc($ressult)){
for the timestamp
$rowz=['timestamp'];
for the time the user insert a data
$rowz['time'];
}}}
this is the output of the timestamp
2019-03-10 22:41:26
and the output of the time is up to you
now I want to create an alarm in that timestamp or time. that will notify the user 4 hrs from now. For ex. user sends in data at 5pm then admin accepted it at 6 it will notify the user like (4hrs from now please pay or else deleted which has a timer 6-10pm )is it possible using php or js?
or should I delay the popup of the data by 4 hrs from now? like I select * in db then popup only 4 hrs from now based on the timestamp or time
my way of notification is inserting data into the db name notification then I just select * and display it
the sleep function works in this like
if(isset($_POST['bla'])){
sleep(10);
$bla=$_POST['bla'];
$sql="INSERT INTO checkout(fname) VALUES(?);";
$stmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
echo "error in sql";
}else{
mysqli_stmt_bind_param($stmt,'s',$bla);
mysqli_stmt_execute($stmt);
}
}
even if the user delete the browser it will still insert the data into the db after 5 seconds

Web Notifications API - Only show once per period

I'm writing a web app that needs to send notifications. It checks 12 different things every 30 seconds and if one of them meets the criteria it should send a notification; it then shouldn't send another notification until the next 30 minute (on the hour and half past the hour) interval. How do you check if a notification has already been sent and not to send it again? I thought this was done via tags but two notifications with the same tag will still pop-up, the second will just replace the first.
The function used to generate the notification is
function randomNotification(whoisit, tagtoPass) {
var message = whoisit + " is getting a notification";
var options = {
body: message,
icon: 'logo.png',
tag: tagtoPass,
}
var n = new Notification('Website Says:',options);
setTimeout(n.close.bind(n), 5000);
}
That function is called from another script that is loaded via Ajax every 30 seconds. That script checks the database to see if one of the 12 things is in a state that requires a notifications then calls the function and passes the name and a unique tag for that 30 minute interval.
Also I've noticed with this code, which was based on the developer docs from Mozilla on Notifications API, doesn't add the notification to the OS X Notification Centre.
Have you considered using a flag in localStorage to store the time when the last notification was sent?
Let's say that you store the time when you send the first notification, then check it again and if it's old enough you send another one and update that flag.
localStorage data will stay even if you refresh the web page.
Example:
localStorage.setItem("last_notification", timestamp)
localStorage.getItem("last_notification")
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Sending Ajax Call When User Exits

I want to remove user stored data in my database when the user exits the page. A window dialog box will come up asking if the user really wishes to exit the page. Upon confirming to leave, an Ajax call should be sent to PHP confirming the action. Is it possible for PHP to receive the call in time and execute the command? If not, are there any other ways to verify that the Ajax call is sent successfully and the command is executed?
If you need very short-lived data (only relevant while the user is on the page), a database is not the right tool. Databases are designed to store long-lived data.
I suggest you use sessions instead. Here's a quick intro. Basically, sessions allow you to persist data across http requests, but to expire that data after a short while.
Start the session when the user logs in or opens your entry page, and store in $_SESSION any data you want to access while the user is on the page.
entry or login page
<?php
if(session_status()===PHP_SESSION_NONE) session_start();
... work through your script
//store data you'll need later
$_SESSION['username'] = 'Linda';
$_SESSION['age'] = 22;
$_SESSION['expires'] = time()+ 60*15; //expires in 15 minutes
The next time the user makes a request, test whether the session is still active. If so you can get the data from session, and refresh expiration. If the session has expired, you can destroy the data.
protected page
<?php
if(session_status()===PHP_SESSION_NONE) session_start();
if(isset($_SESSION['expires']) && $_SESSION['expires'] > time()){
//session is still active. extend expiration time
$_SESSION['expiration'] = time() + 60*15;
//retrieve data
$user = $_SESSION['username'];
.... run your script
}else{
//either the session doesn't exist or it has expired because the user
//left the page or stopped browsing the site
//destroy the session and redirect the user
session_destroy();
header('Location: /login.php');
}
You should not use unreliable, hacky and annoying methods. The only events that come close to your needs are window.onbeforeunload and window.unload but popups are usually blocked in those events (hence the hacky) and when blocked the remainder code as well.
There is also the issue that closing a tab will fire the events, closing the browser however will skip them and its all dependent if the browser actually supports it.
Perhaps use an ajax call every 5 minutes to detect if the page is still running and update a database with that time.
Now with a server cronjob you should select all rows with a time < now() - 300 and then you should have a list of browsers that recently connected but are not sending any signal anymore.
Or you could save the data in localstorage every 10 seconds so then there is no need to do all this?
Try This:
<script>
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
//ajax call here
}
if (event) {
event.returnValue = message;
}
return message;
};
</script>

Counter Box, Visible for all clients

Hello I need a button for my website, that will start a countdown from 60 secounds to 0, then it should display some text (lets drink, cheers) and go back to start button.
All users must be able to see this countdown, so that when a user start the countdown other users can see this.
It should also display a counter, of howmany user have clicked the button, and joining in on the "button"
I have looked into this, but i need to do Ajax / javascript pulling.
Since my programming skill is still on copy/paste/edit level, I do not know howto get started, I can build the timer, but dont know howto do the pulling.
can anyone help me get started.
Regards
René
Well first of all, you need a stateful backend, to store a usercount. So php+any db.
you mentioned socket.io, build on nodejs.
With nodejs this aint this difficult, because its a single threaded runtime, so you can share variable values to different clients.
your nodejs have to listen to 3 urls:
for passing the basing page ( can be done without nodejs, just url to html)
ajax url for passing clicks on a button from client to backend, returns current count
ajax url to pass the current seconds, returns current count and connected users.
everytime the 2. channels gets called, you need to check , if the countdown is alrdy running. if not: start it, else increase clicked counter.
like this:
//nodejs code
var currendSeconds=60;
var connectedClients = 0;
var threadid;
function clientClickedButton(req, res){ // 2. url
if(currendSeconds==60 || ) {
threadid = setInterval(function(){
currendSeconds--;
if(currentSeconds == 0){
clearInterval(threadid);
}
}, 1000); //your counter
}
connectedClients++;
res.send(currendSeconds);
}
your clientside have to listen to click event on the button, send a ajax req to 2.url and display the returned seconds ( from now on our dont need to request the seconds, just set up a count down clientside, without requesting the current seconds. )

Categories