PHP Ajax: Perform action when database is updated - javascript

What I want to do is, when something new comes into the database, it gets the latest value entered and plays a specific song depending on what it says.
For example, on my computer, I run this website. Say somebody else around the world picked up their phone and clicked to play a song, that song would automatically play on all devices running the page. When somebody chooses a new song, the song should change.
I have made several tries at this, mainly trying to use setInterval in JavaScript however it just updates and updates all the time as you would expect.
I guess what I really am looking for is a way to track when the database has been updated, any solutions or code examples I can use?

If I understand you right, you can use push notifications.
https://firebase.google.com/docs/notifications/
Here's a tutorial how to set up a js client
https://firebase.google.com/docs/cloud-messaging/js/client
In this case you won't have to do unnecessary requests to the server to fetch updated. Just send a push notification to the client and do necessary actions on the client side.

Related

Building a javascript web analytics tool from scratch

I am fairly new to javascript, I do know basics. I am looking to build my own (from scratch) java script library just like google analytics.js that will track user behavior on websites. Basically I'm looking to collect data like
Click through data
Dwell time
Page hits etc..
I spent lot of time trying to find website/tutorials to get me started on this but I keep ending up on google analytics.js or some private tools.
What I am looking for :
Is there any good starting point/resource/website which can help me build this js library
Are there reference for archetecture of end to end system including back-end?
Any open-source library that I can directly use?
Some things I already looked into
Chaoming build your own analytics tool
Splunk BYO analytics
At it's most basic, the architecture of such an application would only require a client, server, and database.
You can use basic javascript functions to record specific user actions on the frontend and then push them to your server. To identify your users you can set a cookie with a unique id. Then, everytime you send data to your server, you will get the specific user request as well so you can keep track of their actions. (Be careful of privacy laws first though).
For page hits, simply send a response to the server everytime someone opens your site - so call this function as soon as your Javascript loads. On the server, send a request to increment the appropriate value in your database.
For user dwell time, write a function that records the date when the user first hits your site and then count how long they stay there. Push your data to the server every so often and save updates to the user record by adding the new time spent to the current time spent. You could also watch for when a user is about to exit out of the site and then send the data all at once that way - although this method is more fragile.
For clicks and hovers, set up onclick and mouseover event handlers on your links or whatever elements you want to track. Then push the url of the link they clicked or whatever data you want - like "Clicked navbar after 200 seconds on site and after hovering over logo`.
If you want suggestions on specific technologies, then I suggest Node.js for your server side code and MongoDB for your database. There are many tutorials out there on how to use these technologies together. Look up javascript events for a list of the different things you can watch for on the frontend.
These are the building blocks you need. Now you just have to work on defining the data you want and using these technologies to get it.

Electron. Autoupdating app when it notices the change in the database or selected server?

My client wants applications written in electron which works both offline and online. The application is to connect to the server / database and download data (photos and descriptions of products) so that it can work in the offline version. When it is online, the application checks whether there is any change on the server / database and then an update occurs.
I have already prepared such applications (search engine and product filters with the possibility of generating pdf), but I have no idea how the application would check whether the server existed any of the data and download new photos of products, etc.
Yeah well the question is: Do you want to run you're queries on the Client it self? Because then, if not strictly restricted, someone finds a way to open up the console and sends funny queries.
But anyway... your question:
The easiest way I can think of this, because we don't want to download everything again, is to have a version number for each element.
So the client has one and if that does not match the servers it gets updated. Now you just have to get all IDs. But keep in mid, you still have to handle what happens if an item gets removed or a new one added.
This is not really an answer but I hope it inspired you a little bit.
Oh some after thoughts:
You could get something like a WebSocket between those two. Yes you had to program one more service but
The query would be save
You could keep track of removed and added items
You could work out some timestamp system that you get all items that are newer than the timestamp of the client.. this will be some work though.
nice day, Elias

Persisting a JavaScript setTimeout function call across postbacks as user browses application

I believe I can use utilize the following functions to create delayed JavaScript alerts:
setTimeout(), clearTimeout(), setInterval() and clearInterval()
But how can I use them accross postbacks. For example:
A user has a list of reminders stored in the database. When user logs into site I can access those reminders and call something like:
setTimeout(function() { alert("Reminder 1"); }, 10000);
Depending on when the reminder due date/time is.
However as the user switches pages before the alert notification happens I believe the setTimeout call won't persist.
Is the only way to get this to work to look up the users reminders on every single postback and do a setTimeout on every page or in some sort of master page?
This is not really the way to do this. If your trying to build some sort of notification system then ideally it should be driven server side.
In a normal multi-page site every time you render a page the server would check for notifications and then in your template render an alert or some UI feature that tells the user they have notifications.
That set-up won't be active, IE if a new notification is posted on the server the client page won't know about it. Unless you use a notification message api for example pubnub.
Something like pubnub would let you send the message to your page, and in your JS code get a callback, so you can render it in your dom.
Since you have a multi-page app you would need to fetch / request for the notifications on every page render. Running a timeout to trigger for an ahead of time moment is not an ideal solution.
Another way to do it is to poll your server from your js code say every 5 mins and ask for notifications.
That has a price tag on all those repeated calls to your server. The best bet is to use something like pubnub but that comes at an extra laden of code server side to make it work.

An alternate way of reloading a chat after few seconds

So I was implementing a chat room. I'll start off with the schema that I used.
I have a room table, that basically stores the information regarding the chatroom like the number of participant, the topic etc etc.
I have a users table that stores the users info.
I have a posts table that stores the posts. This has a foreign key from Users and from room tables.
also, I have one final table that is to have a relation between users and rooms. So it just has the roomid and the userid from the users who are a part of the room.
Now, I have three divs on page, one for the chatarea, the other where the people online are shown and then there is a text area to post the message.
What I am doing currently is, to have a javascript function loadChats(), now this method calls a php file that just fetches all the posts in that particular room till now. And the same is dumped into my div ie "chatroom".
Also, similarly, I have a loadParticipants() that load the users every other second.
I am using jquery.post for the purpose and in the end of the method, I do a setTimeout in the end of the function. Now here are my questions
Ofcourse i can make this better. Any suggestions? I was thinking of a few.
On every call to php, I get the entire chathistory and send it back to browser, ofcourse I can check if the count of messages is the same as it is on the client side, and if it is, then I wont send the messages. But is it going to make it any better? How?
Also, making a call to server side every other second seems a bit too much of an overkill. Is there any way to do it like, if some new chat is added to posts table, then that particular chatroom is notified and updated? i.e. instead of constantly pinging the server to ask for new request, just ask it once, and wait if there is anything new or not. When that request is completed, it pings the server again for the next update.
You should look into websockets (I've never used them with PHP but this seems really promising: http://socketo.me/). What you can do is have the server push any new messages to the client whenever they come in, and have each of the clients push to the server, etc. This way you won't have to keep pinging the server over and over every 2 seconds, and loading tons of data to compare. When there's a new message, the server saves it to some database and then pushes that message through all the open sockets. Same thing with logging in/logging off.
edit: Just looked through the page even more and their tutorial even goes through how to get it set up with a basic chatroom-esque functionality.

How to update asynchron pages upon event from other client?

I'm currently fooling around with AJAX. Right now, I created a Markdown previewer that updates on change of a textarea. (I guess you know that from somewhere... ;-) ).
Now, I'm trying to figure out, how to update a page upon an event is fired from another client. So to say an asynchron message board. A user writes something, an event is called, the post is written.
But on the other clients' pages, the new post is of course not yet available until they reload and get the updated list of posts from the database.
Now, how can you get this to work asynchronously? So in that moment when one client does something, the other clients all get to know that he did something?
I don't think this can be done completely in AJAX, but I also have no idea whatsoever how to implement this on server-side, as it would require a page reload to inform the other clients of the event.
I'm thinking of creating a file or database entry that hashes the current state of data. Whenever a client loads the page, he saves this hash. Then, a timer (does this exist in JavaScript?) checks for the hash every few seconds.
As soon as anyone changes the databse, the hash is recalculated. If the script sees that the hash was changed and is different to the one saved, it reloads the contents form the database and saves the new hash.
Is that even going to work?
Polling that is light as possible is really the best solution here. Even if you did use a socket or something... That's still basically a live connection waiting around that will likely have to poll itself (albeit in a more effecient way).
20 queries in 10 minutes that have responses like {"updates":false} shouldn't even be putting a dent in your application. I mean imagine someone browsing your site requesting 20 pages and the related images/scripts/etc (even if some caching is involved), there could easily be hundreds of requests requiring all sorts of wasted database queries to information to be displayed on the page they don't actually care about.
You could use polling. For example each client might be sending continuous AJAX requests to the server say each 30 seconds to see if new posts are available and if yes, show them:
setInterval(function() {
// TODO: Send an AJAX request here to the server and fetch new posts.
// if new posts are available update the DOM
}, 30 * 1000);
On the other hand when someone decides to write a new post you send an AJAX (or not AJAX) request to the server to store this post in the database.
Another less commonly used approach is the concept of Comet and the HTML 5 WebSockets implementation which allow the clients to be notified by the server of changes using push.

Categories