I want to fetch some data from mySQL without refreshing the page using jQuery. Can someone please tell me how I can fetch the data if any record in mysql table is updated. For example, following code fetches a number count from the database, if someone add a number in the database and it is updated, how I can display the new number without page refresh? Thanks.
<?
$query = "SELECT number, name FROM members WHERE id=1";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$number = $row['number']; ?>
It’s been mentioned two times already, but I still want to underline it. You would never want a client to be able to access the database directly. It is a serious security risk.
Now to the solution. First of all you will want to set up a PHP-file that you can request with ajax. Let’s call this
check.phpand it will look something like this:And now onto the JavaScript. The solution is similar to that of Kyle Humfeld, but will not be using the
setInterval, because it’s a really bad practice. The reason behind this is becausesetIntervalwill not care about the status of your ajax call, if it has finished or not. So you might end up with stacking requests if there’s something wrong with the server, and this is not good.So to prevent this, we instead use a combination of the
success-callback of the ajax method (.getJSONis essentially a shorthand for.ajax) andsetTimeoutto create something that’s called polling:Also, there’s a more advanced solution using a comet server that will push data from the server to the client, but you should try to get the above to work first before digging into comet. If you want to read up on the subject I suggest that you take a look at APE.