开发者

Reload AJAX data every X minutes/seconds, jQuery

开发者 https://www.devze.com 2023-01-01 02:19 出处:网络
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

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) {

                    开发者_如何学Python        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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消