Marc De Joya
Marc De Joya

Reputation: 31

How to automatically detect changes to database and produce a jquery notification?

In the website I am maintaining, I wan to add a new feature which functions like the facebook notification. I want to automatically detect changes in my database, then if a new item was inserted/updated then it will produce a notification.

I found this: http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html

It uses Jquery to update a div automatically. I tried it, modified, and it worked :)

Upvotes: 3

Views: 14290

Answers (3)

Naryl
Naryl

Reputation: 1888

You can do that with a trigger but I would do it a much simpler way:

1- When someone does the needed insert/update, in the same script insert a row in a dedicated table, let's call it notifications, for each notification you want to send, it would look something like this:

 notifications(id, user_id, message, status)

2- Then have a cron job executing every X time that reads said table and sends one notification to the user with said user_id and deletes that row from the table (or sets it to "sent" if you want to know what did you sent).

EDIT: crontab example, executing something every 3min.

first type crontab -e to edit, then insert the following line:

0 */3 * * * complete_path_to_the_script > /dev/null

Upvotes: 0

VettelS
VettelS

Reputation: 1224

There's a technique called comet (or long-polling) that will help you achieve this. What you don't want to be doing is polling the server (via AJAX) every x seconds to see if the data has changed- it's wasteful and resource-intensive. Basically what comet does is poll the server to see if there are any new changes to pull, and only when there are actually changes does the server respond. It means that you only hit the server when there is actually new data to be pulled.

It's easy to implement in JavaScript, but since you mention jQuery in your title, there is this plugin that may be of use.

Upvotes: 1

Qurben
Qurben

Reputation: 1316

For instant notifications you'll need WebSockets, like Ratchet for PHP.

Detecting changes in your database is not easy to implement, easier would be to send a message in PHP when you also update the database.

For this you'll need to create a websocket connection with everyone currently visiting the page. When someone updates or inserts, a message will be sent to all connected users.

Check out this page for a simple tutorial http://socketo.me/docs/hello-world

Upvotes: 3

Related Questions