I programmed a CMS that has a log of who has recently logged into the system. Presently, this data is fed into a jQuery UI tab via Ajax. I would like to put this information into a sidebar on the main page and load it via AJAX every 30 seconds (or some set period of time).
How would I go about doing this? Does the PHP response need to be JSON coded? I am fairly new to AJAX and JSON data.
Here is the PHP I am currently using to pull details from the users table-
<?php
$loginLog = $db->query("SELECT name_f, name_l, DATE_FORMAT(lastLogin, '%a, %b %D, %Y %h:%i %p') AS lastLogin FROM user_control ORDER BY lastLogin ASC LIMIT 10");
while ($recentLogin = $loginLog->fetch()) {
echo $recentLogin['name_f'] . " " . $recentLogin['name_l'] . " - " . $recentLogin['lastLogin'];
}
?>
Thanks! UPDATE
Okay, this is what I have so far.. the part I'm stuck on is how to loop through JSON and enter it into the box. It works fine as long as I use just one result and assure it is not in [ ]'s. I'm just learning Ajax and JSON, for some reason it isn't coming to me too easily.
Javascript -
$(document).ready(function(){
function refreshUsers(){
$.getJSON('json.php', function(data) {
for (var i = 0; i < data.length; i++) {
$("#loadHere").html('<p>' + data.name + ' ' + data.lastLogin + '</p>');
}
});
}
var refreshInterval = setInterval(refreshUsers, 30 * 1000);
refreshUsers();
});
What my PHP script outputs -
[{"name":"Joe Smith","lastLogin":"Fri, May 21st, 2010 08:07 AM"},{"name":"Jane Doe","lastLogin":"Fri, May 21st, 2010 07:07 AM"}]
Thanks!
remove/delete the rows (rows() then remove()). re-draw the table again (draw()).
Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.
PHP side, use json_encode().
Client side, use $.getJSON():
function refreshUsers(){
$.getJSON(url, postData, function (data, textStatus){
// Do something with the data
});
}
// Keep interval in a variable in case you want to cancel it later.
var refreshInterval = setInterval(refreshUsers, 30 * 1000);
With these 2, you should have a lot to get started with. More than this, you'd be asking us to work for you :)
The simplest way (whether its the best way is subjective - for the use case you've presented I'd say its fine) would be to do:
var updateInterval = setInterval(function() {
$('#whereIWantToDisplayIt').load('/thePathToThatScript.php');
},30*1000);
Every 30 seconds, this would load the output of your PHP script, and put that output into the element with ID = whereIWantToDisplayIt
I prefer Seb's answer though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With