How can I make this script refresh with ajax whenever a table updates ?

I have this script that pulls post data from a database and displays it on my site. I need this to update in real time with Ajax whenever the topics table updates. I know literally nothing about Ajax. Can someone assist with this please?

<?php 
 
//connect to the server
$connect = mysql_connect("localhost","","");
 
//connect to the database
mysql_select_db("");
 
//query the database
$query = mysql_query("SELECT * FROM topics ORDER BY last_post");
 
//fetch the results / convert results into an array
 
WHILE($rows = mysql_fetch_array($query)):
 
$topic_id = $rows['last_post'];
$topic_title = $rows['title'];
$reply_author = $rows['last_poster_name'];
$reply_time = date('h:i A', $rows['last_post']);
$reply_date = date('l, F d, Y', $rows['last_post']);
endwhile;
 
echo "The last post was made in <font color='blue'>$topic_title</font> by <font color='red'>$reply_author</font> at <font color='green'>$reply_time</font> on <font color='brown'>$reply_date</font>.";
 
?>

It’s really not about AJAX. There aren’t any simple solutions to server push.

Most solutions are based on polling every n seconds to see if there are updates.

It’s not AJAX , it’s called “Cron Jobs” that updates records on basis of timing intervals …

What you’re looking for is web sockets.
ie http://socketo.me/

Two separate things. Cron Jobs tend to be for scripts run without a user, at timed intervals. Polling is different.

Yes, CRON jobs are NOT what he is talking about. I see two ways of handling this. Either just place a simple
button on the page and label it “REFRESH” and let the user refresh the page whenever they want to, or use
AJAX to reload the data every so often. You can set up a timer to automatically call AJAX to load an external
page and place it into a

. Just have the external page pull the latest data from the database. There
are a few issues with that. Some timers do not work on some user’s browsers due to JS being shut off and
this also means that every user is using server resources on the timer which can cause issues if there is a
large number of users on the site. One other possibility is to just use a timer to refresh the page every so
often.

Well if he wants to update the clients data whenever the backend table updates he will have to use web sockets. Polling with ajax is so 2010… :stuck_out_tongue:

LOL, must be the Christmas spirit, but, I have found a lot of smiles on comments today! Yep, 2010…

But, doubt he gets websockets… Maybe… In case he wants to look into it, here is a tutorial on it…
http://www.phpbuilder.com/articles/application-architecture/optimization/creating-real-time-applications-with-php-and-websockets.html

Ratchet also has a tutorial on their page ^^ Seems better so I’d still suggest using that. (never use a lib without tests ;))
http://socketo.me/docs/hello-world

Sponsor our Newsletter | Privacy Policy | Terms of Service