Reputation: 3141
So right now, I am doing a GET request every second, to check if there is new information in database.
This is using a lot of resources from the user's side. I have a textbox which shows the current data. If there is new data in database, it will be replaced with the new data. For now, I'm doing a GET request every second to achieve this.
Is there a better way to do it?
For example: I looked in the inspection window and watched stack overflow. It wasn't doing any GET requests. But once there was a new comment, it updated with the new comment. I want something similar to that.
I have researched on Stackoverflow and haven't found the one that is helpful for the application I'm making.
My current code:
function timers() {
tmrAjax = setInterval(function () {
$.get('<?php echo base_url('home/get') ?>', function (html) {
$("[name=text]").attr('id', 'text');
$("#text").val(html);
// $("#text").removeAttr("disabled");
});
}, 1000); //a call every second is ridiculous!
}
timers();
$(window).blur(function () {
clearInterval(tmrAjax);
$("#text").removeAttr("id");
// $("#text").attr("disabled", "disabled");
}).focus(timers);
Upvotes: 1
Views: 869
Reputation: 167210
The concept that happens in the StackOverflow Website and the AngularJS is called WebSockets. A traditional HTTP AJAX Long Polling can be compared with the WebSockets this way:
(source: jensimmons.com)
And WebSockets have a persistent connection with the server. Which means, server always knows when there is a change in data, and it pushes the data to the client, instead of client pulling (requesting) the data from the server, which is the traditional way.
As you can see, WebSockets are same, but goes by frame by frame. They take chunks. Only chunks of data are sent to the client, thereby saving a lot of time and bandwidth:
(source: rabbitmq.com)
Upvotes: 3