In my application I want to send some alerts to the client. I want to send updates to client without a request similar to push server.
How can I do this?
The best way to handle notifications without a permanent connection is to use what people refer too as a heartbeat function.
A heartbeat function is a function/method that gets called on a interval repeatedly just like your heart beats in a constant rhythm.
setInterval(function () {
$.get("/heartbeat.php", null, function (response) {
// check the response from heartbeat.php for new notifications
});
}, 10000);
Note: The above example contains jQuery code $.get( ... )
, the non-jQuery way would be to make your ajax call using XMLHttpRequest
.
The above would call the php script every 10 seconds to check for new notifications. New notifications can be added such as using a table inside a database. For example having a notifications table and 3 (4 if you want a date) fields: a user identifier field, message field, and a 'read'/'sent' flag field.
New notifications would get added to the table, and when the heartbeat script is called it'll check the user identifier and flag fields for new messages; if any are found then respond back with the message and mark it as sent.