Make button enabled for only one user on webpage - javascript

I'm developing a website that is suppoused to control some devices that rotate when pushing one button. However, I only want one user at a time to be able to push the button.
That is, when a user enters the page, check if it is the "first" or only user that is there. In case he is, he can use the button freely. In case he isn't, the button appears as disabled.
What would be the best way to implement this? I'm using a classic design of html+js+php.
Thank you.

This is a design question, and still, you should have already tried something and post that something before asking here.
You should use a lock system:
create an endpoint with php, to call with Ajax that checks over a variable globally shared (better if on db) that acts like a semaphore, the first who arrive make it red and 'acquire the lock'.
If the lock is acquired, the client can do the action,
If the lock is not acquired, someone else took it already.
Do not forget to release the lock after the action.
You can use the same call to acquire the lock, do the action and release the lock. If the lock is not acquired the call return an error message and the user will know which is the issue.
P.S.
If you was thinking about a real time system, you may consider using websockets or just the system above with different calls for acquire the lock and do the action (and poll for the lock status).

To track a user on a website is not that difficult, but check if and when he/she leaves is the challenge.
If this is not time crucial you can do this with timeouts.
First, you need to be able to track the current user on your site (maybe with sqlite, textfile, mysql/mariadb) (maybe identified by IP) wich is updated a user loads the page.
After a timeout the tracking storage can be updated and the next or new one can hold the button.
If you need this realtime, you need a bit more to do. In this case I would use Websockets or NodeJS to keep connections to your page wich in fact you can use to keep track on active users and wich one should be able to keep the button.
Just keep it like a realtime online chat without texting. There you need to keep track of online users as well.
(Websockets or NodeJS are here only a example, there are alot technique to archive realtime "collaboration".)

Related

Time Spent by user on a web page + Iframe

I want to measure the time spent by a user on web pages. It's doesn't include the time when a user navigates away from the browser.
I found few open source libraries like Timejs library which can measure the time spent by a user on a web page, but when a user is watching a Youtube video on the page, these libraries don't measure that time.
.
Is there a way to handle this case or any other library which handles this case?
Actually, these libraries fail to calculate the time spent by the user inside an iFrame.What is the best way to know when a user is active in an IFrame?
How does Google/AppNexus/Motomo calculate interaction time? Is there a common design/architecture that they follow?
PS: I am trying to integrate the library with my react App. If there exists any similar method to solve this problem in React. Please let me know in comments/answers.
Thanks in advance
HTML5 Page Visibility API is the answer of your question.
You need to just listen an event as per the browser and it will be triggered every time when user will jump to another tab.
Look to Page Visibility API
There is a good and security way to do it but you need webSocket implementation.
Make special socket client and server for this feature.
When you client is disconnected you can count that your user is not anymore on page. Implement timer's for time log on server part.
Page Visibility API look like solution for local calculation(unprotected). If you work with money or some kind of value's better use server for validation.
p.s.
If you have a buggy situation with timer ( on inactive tab ) then use HackerTimer library (combination with web workers).
Just start a timer when the user enters the page (lots of ways to do this) To pause and continue the timer, try using the onunload() and unload() events (they may not work exactly as you want it to, but it is the best thing I could find. Take a look at this to help you https://www.w3schools.com/jsref/event_onunload.aspHope this helps!

Getting live notifications when users register

I'm looking to create a notification system for when someone registers to my site. The type of notification system I am wanting is something like stackoverflow has or Facebook. I want a number type notification to appear of how many new registrations I have, but once I click to view the notifications (new registrations) I want the notification alert (like the red square stackoverflow has) to go away.
I am writing this with PHP and have a db table called users that I can pull the users from. I'm just not sure how I can have a notification like this without selecting all of the users to give me a quantity?
So say I have 20 users and 2 new people just registered. I want a notification to display with the number 2. Then when I click on it, for that notification to go away.
How could I go about doing this?
I am designing systems like this.
The way I do it is to have a structured log of events written by the application into a messaging queue/message broker.
Then I have a message consumer that reads the events and updates any metrics I want out of the system.
In this case, you would need a message consumer that decides on what users should receive what messages (some messages could go to all, some only to specific people).
Each user would have to either poll an API that serves these messages, or have a websocket open to receive the data as a stream (this is faster).
I would place an intermediate storage between the message consumer and the API. I would recommend something light and fast, like Redis, for this.
This is a lot of infrastructure to set up, there are other quick and dirty solutions, but this is quite minimal in my opinion.
Assuming each users have an unique ID, you can achieve it very simply by yourself adding very few PHP code.
Answer will definitly depend on your own needs and complexity degree you want to achieve, #firelynx answer can be really great if you want to achieve something big and evolvable (you can definitly have some great fun and learn a lot).
However if you only want a very basic implementation I suggest you to create a "notifications" table in your database, you can use (as a minimum) columns [id, user_id, message, new] where new is a tinyInt or any equivalent.
Then add some notifications to the user(s) of your choice, new should be 1 by default. When the user see the notification, just set new to 0 for related notification(s).
Selecting users that should receive those notifications can then be done depending on user group or some conditions.
If you wanted something simple and not so shinny to begin with, that should do the job well, you can also add a "icon" column to add some fun.

Javascript Best Practise: Syncing Browser Windows

I have an html5/javascript application in which multiple users can be viewing the same set of data of any given time. For the sake of a real world example, lets say its a calendar type page.
So user1 is looking has the browser open and looking at the calendar page and user2 is also on the calendar page. User2 makes a change to the calendar and i'd like (as quickly as possible) for those changes the be recognized and refreshed on user1's screen. What is the best way to do this?
I'm thinking about have a mysql table for active users that stores the page they are currently on and a timestamp for its last update, then use ajax calls to ping the server every few seconds and check for an updated timestamp, if its newer than what they have client side, the new data gets sent and the page "reloaded." I am putting reloaded in quotes because the actual browser window will not be refreshed, but a function will be called via javascript that will reload the page. Sort of the way stack overflow performs its update checks, but instead of telling the user the page has changed and providing a button for reload, it should happen automatically. If user1 is working away on the calendar, it seems it might be quite annoying for user2's screen to constantly be refreshing...
Is this a horrible idea? Is pinging the server with an ajax request every few seconds going to cause major slow downs? Is there a better way to do this? I would like the views on either users side to be real time because its important that user1 not be able to update an element on the calendar page that user2 has already changed.
Update: based on some web sockets research it doesnt seem like a proper solution. First its not compatible with older browsers and i support ie8+ and second i dont need real time updstes for all users on the site. The site is an account based applicatiin and an account can have multiple users. The data needs to sync between those users only. Any other recommendations would be great.
You need realtime app for this. You should have a look at socketio. Everytime a user log in, you make him listen for changes on the server. Then when something changed on the server, every users listening are notified.
you can find examples on the official website : http://socket.io/

Most Efficient Way to Count Clicks

I'm starting to run a few ads on a website, and I'm trying to decide the best way to track performance.
Specifically,
What's the most efficient way to count clicks? About the only way I can think of is to link the ad to another page with the ID of the ad as an argument (e.g. adserver.aspx?id=1234). The other page would then update the database and do a redirect to the advertiser's link. However, it seems inefficient to have to load a separate page for this. Are there any other options?
Also, it seems like I might need to know stuff like how many clicks occurred in a given week. But storing a separate database row with a date for every single click seems excessive. Has anyone else done something like this? Would it make sense to maybe create a new row for each week and increment a counter for all clicks that occurred that week?
Any tips appreciated.
I would suggest that your first solution is the best option, in fact it is the design that most similar systems (OpenX, Google AdSense etc) employ. Additionally it helps you better managed your banners and prevents your site leaking search engine spiders.
As for performance that is just a question of having a good design, in a typical design the redirection script will be fairly lightweight so should process requests fairly quickly. It is worth mentioning that you could thread off the DB updates to reduce the redirect request response times.
There is of course another option:
Rather than homebrew your own banner serving scripts look into implementing OpenX instead, it is free and an extremely good piece of software. OpenX can be found here:
http://openx.org/
and here for the open source version you can run on your own server:
http://www.openx.org/publisher/open-source-ad-server
Another option would be to implement something like Google AdSense and save yourself the hassle of finding advertisers etc. Google also provides tools to allow you to sell banner space and then fallback to default AdSense banners if you have no active advertisers (OpenX will also do this and also support integrating AdSense (and other advertisers))
You can do it with JavaScript.
Opening the page:
Send the ad URL to the client
When the user clicks the ad, use JavaScript to open the URL. Or, simply use an anchor with target="_blank".
Logging the click:
Either way, hook a JavaScript function to the ad click event.
When the user clicks the ad, use AJAX to call a web service. The web service will then log the click.
This way the ad opens as soon as possible, then the browser asynchronously communicates with the server for logging.
The question is, what happens if the user clicks the ad, the page opens, then the web service call fails? If you would prefer, you could call the web service first, then and only if the call succeeds, open the ad. Probably not the best from the end user's perspective.
For you question #2: Storing each click gives you the most reporting flexibility later. If you are set on weekly reports, why not set up a weekly process that generates the reports you need, then cleans up the data? You could even skip cleaning up the data for now until space or speed becomes an issue.
Would it make sense to maybe create a new row for each week and increment a counter for all clicks that occurred that week? Probably not. Only one process can update the counter at a time, otherwise you'll lose data. The locking that has to occur to get the value then update it will probably significantly slow down.

Security question: Using ajax and events to keep session alive

I know a few sites (such as my bank and my school) that kill a session after their has been idle for a set amount of time. It is my understanding that session activity is determined by users following links or at the very least from some kind of active interaction, like updating a form via ajax. Basically the server gets a request to do something during the session and goes ahead and extends the session time another 15 minutes.
But on some occasions I have lost major amounts of time and info while filling out a text box or reading some long set of instructions along the way.
So why not have an ajax script that listens for keyboard activity and mouse movement and lets the server know that the user is still there and active, even if they aren't clicking a submit button or following a link?
I was wondering if anyone knew of respectable sites that already do this, or if I was overlooking some major security hazard with this idea.
The only thing I can imagine would be risky are the random acts of cats, vibrating electronics nearby, or a hyper child.
But in all of the above, the user is most likely at home and -- unless they are trying to get exploited -- have probably minimized the window and thus these things are very unlikely to trigger as an event.
Does anybody see any other major risks?
Typical AJAX sites are making posts back to the server anyway. These events are renewing the users session already.
If you put these events on keyboard or mouse clicks, how many times are you going to be posting to the server? If I am typing in a form field like I am now, that means you could potentially have a ping to the server for each letter I type; not a very efficient solution. On the other end, what if your user is just sitting their reading or using an external text editor to type their text into and will copy it into your form later.
I think the more typical solution to provide a friendly UI so that long posts do not get dropped because of a session expiration is to use an auto-save feature. Google Docs does this. Every few seconds/minutes, they post the contents of the editor back to the server without the user actually clicking save/submit. The other option is to inform the user that their session is about to expire (could be done with a javascript timeout). Provide a link to ping the server to renew the session.
Your solution lends itself to the same problem: you are relying on user behavior. In the first case, navigating between pages and in the second, mouse clicks.
I used to work for a company that did a lot of online contests where users would have to enter essay content as well as shorter blocks of data; we used to modify the session time out "session.setMaxInactiveInterval()" for the user's session when they hit the "long-winded" page so that they would have more time to edit, and then we would set it back to normal after the submit.
Later at that company and a couple others I worked at I proposed a solution similar to what you are describing, but for various reasons it was never accepted. It was never considered a bad idea, just not one we chose. Basically it was going to be an ajax call on a timer so that just before the session timed out, it would fire off a light-weight ajax "ping" and keep the session alive as long as that page was open. I have never had the chance to implement it in the "real world" so perhaps there are negatives that I have not thought of.
Good luck.

Categories

Resources