Auto refresh content after changes in database – AJAX
There is new and improved version of this idea! If you interested go to
Volume II of ajax refresh with working example
If you need basic idea of Auto refresh see post: “Refresh content automatically after some period time – jQuery“.
In one of my application modules in my engineering thesis i had to ensure that end users always have current list of messages. It was very important because messages can be edited, hidden, published again, and a user does not have time to remember to refresh the page. Of course, it’s not a big deal. I set the time after which page must refresh and everything is working as intended.
Because of a specific character of the user, that time cannot be shorter than half a minute. The page always refreshing every half minute with:
HTTP request-> database query -> result formation -> result sent to the browser
It’s insane. And with hiding the content of about 10-20 messages, just after the beautifully formed list appears, we reload page once again.
The solution maybe a little crudy, but for my needs it worked well enough.
Idea
Create a counter stored in database and HTML code. With each change in the list of messages (regardless of the action – edit, add, hide) i increase counter in the database. Then, instead of getting entire list or refreshing a page, every half minute in the background im checking counter and compare with the one hidden in code. Page is reloaded only when these values are different.
And everyone is happy. Of course query path will not change. However the query time and the result formation will be significantly reduced. And most important, user will not want to shoot me ;o)
Tools
PHP, HTML, prototype
Preparation of HTML
In <head></head> section we are attaching prototype framework.
Somewhere in <body> section – ideally at the beginning – we are going to need two containers, with an assigned id, invisible for users.
For example:
old_count – will keep the state of the counter after page is loaded.
new_count – will keep the state of the counter after next request.
It doesn’t matter if it will be <div>, <p>, or anything else. It is important that it has an id.
And of course we need container for our message list.
<div id="msg_list" style="display:none"></div>
Because messages are stored in the database, when creating a table i’m automatically adding the row with id=1 where i store my counter. With every modification of entries like: edit, delete, add new, archive, etc – the value in dedicated column will be increased by one.
Since i’m working with classes, i will not go into details of the database connection.
Below I will present only the most important fragments.
– Function to increase the counter
function register_changes(){
$this->db ->query("UPDATE table_name SET counting = counting + 1 WHERE id=1");
}
– the status counter check
function check_changes(){
$result=$this->db->query("SELECT counting FROM table_name WHERE id=1");
$result=$this->db->fetch_array($result);
return $result[‘counting’];
}
The next step is to create a separate file created by AJAX. I will call it checker.php.
It looks like that:
require_once ('class_file.php’);
$refresh = new class_name();
$new_number = $news->check_changes();
echo $new_number;
Preparation of JS
At the begining we are going to create a function, that will execute hidden demand. AJAX is calling the script checker.php on the server. If the counter is increased, the list of messages is refreshing.
Input parameters for this function is:
url – the address/name of the called script
id_st – ID of the container that holds the old counter status
id_nw – ID of the container that holds the new state of the counter
function check(url,id_st,id_nw){
req = new Ajax.Request(url, {
contentType: 'text/html; charset=utf-8',
method: 'post',
onSuccess: function(response) {
//containter update "new_count" with the current value of the counter
id_nw.update(response.responseText);
//assign the current counter to variable new
new = id_nw.innerHTML;
//assign the status of the counter hidden in the HTML code
older = id_st.innerHTML;
//if the values are diffrent, it will refresh the list of messages by Ajax.Updater. Using that function we will refresh only the list, and not entire page
if(older!=new){
//There was a change, rather then refreshing the entire page to the next comparison, we need a new counter value
id_st.update(new);
//message list update.
new Ajax.Updater('msg_list','msg.php');
return false;
}
}
});
}
We have our function, so now we just need to determine how often the counter must be checked and give him an initial value. The initial value is taken with the first query that is receiving the list of messages and in php it is assigned to variable called $start
//Every half minute call a function check
setInterval("check('checker.php',$('old_count'),$('new_count'));",30000);
// When the page is loading we set the initial counter value
window.onload=function(){
$('old_count').update('<?php echo $start; ?>');
}
Nothing more is needed, the list of messages (and only that) will refresh itself every half minute, if only something in its content will change.
Thank for the tutorial, please I also need the tutorial of how to create a anonymous up vote and down vote, I know how to create for user but I’m having problem for non-user, Thank you.
You would have to either use IP or cookie to check if user has voted, both have their pros and cons. But other than that it wouldn’t be that different comparing to registered/logged in users. Instead of checking if user has voted, check if that IP or cookie has voted. IP is less “anonymous” than cookie and multiple visitors can share same IP, but cookie can be cleared or someone can use multiple browsers.
i know this post is old, but.. why use a framework when you can just do the comparison with js ? and update the counter with php too , well i came here so i can get the right way to think it and i got it , but dont need any framework
You mean JS framework “prototype”? If so, then this was actually part of bigger project and I’ve simply used it for other things + it handles AJAX request. You can change it to plain JS if you want to. How you do it is up to you if you understand the basic concept that is behind this ;o)
I'm using codeigniter….
Oh sorry I am asking You Kokers. I wonder if You will be able to implement this…
Hello Julie nice autorefreshing. Thanks, but I've got one question how to open some sound voice after add, update new record in db. I am thinking about how too play something if page is refreshed. It is possible to make it. For some help great thanks. REgards Jim…
Hi Julie. You can find demo, and latest (improved) version of this ideat here:https://aiocollective.com/blog/entry/ajax-auto-refresh-volume-ii the link was at the beginning of the post ;o)
Hi.. Can You Give us the complete code because above snippet are confused how to implemented. So please I kindly request to Give us Live working demo as soon as possible.
Ok ok, I will try to make some demo till the end of the week :o)
Dear Eliza, would you mind to give us the complete code i'm pretty confused in some parts and have no idea how to complete it
There isn’t working demo right now. As soon as I will have some free time I will rewrite the code for jQuery and create online demo. But with the information I gave in the post it should be easy to get this working. The whole idea is explained ;o)
Is there an example of the code?
xd
Why xd?
Maybe because the comment Ronald replied to is 6 years old and demo was down at that time and he didn’t noticed that comment is THAT OLD, and there is an example now, and he thought it was funny/dummy to ask for it when there is an example, but who knows ¯\_(ツ)_/¯ Whenever I see a notification that Adobe XD has a new update I get confused why Adobe is smiling that stupid in my notification, so Ronald’s xd might be just an xd that means nothing at all and it’s just a spam, but someone approved it anyway and… Read more »
Can you please show a working example of this? Thanks