tags:

views:

392

answers:

2

Hi everyone,

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!

+7  A: 

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

Seb
Thanks for your help! I updated my original post with what I have so far. Stuck on trying to loop through JSON - I'm new to both loops in Javascript/jQuery, Ajax, and JSON. Thanks again!
NightMICU
Glad I could help! If this is the correct answer, please mark as accepted so others with the same problem know how to solve it. Regarding looping, remember whatever you have in PHP and encode as JSON will behave exactly the same the other side: if it was ab object, you can access properties in JS using the `.` operator; if it was an array, just iterate as you would in almost language; `data[i]`. Beware of maps in PHP: they become objects in JSON.
Seb
Okay, so I was able to figure out how to loop through the data from JSON and add it to the proper DIV using .appendTo(). But what I need is to just load the results from the MySQL table and insert them into the sidebar DIV every X number of seconds. Mailslut's method actually seems to be better for this - it's simple to loop through the table with PHP and insert that HTML into the DIV. So, my question - what is the advantage to JSON vs $.load() for this application? How could I still use JSON and add all of the results from the table into the DIV without appending them each time? Thanks!
NightMICU
You will need to create the HTML on the fly and append it, there's no other way. But, IMHO, that's a better, more flexible way. See my comments in Mailslut's answer: creating the DIVs in PHP is not a great decision, because you're mixing logic with presentation. In fact, there's no much point in generating HTML inside that particular PHP script, because HTML won't be necessary at all without JS enabled, got what I mean? You can do it anyway and it'll seem faster for you, which will be, but not flexible at all if one dev is in charge of PHP and another of JS.
Seb
Hi Steb, I may not have been clear in my original post. Basically, I just need to inject the freshest rows from a MySQL table into my sidebar DIV. The PHP itself does contain HTML for the paragraph structure but it does not add DIVs, nor does it create the parent DIV that the data is loaded into. This is for a CMS system that will only be used by a handful of people, they have all been advised that JavaScript is required because the system relies so heavily on it. Like I said, I cannot figure out how to update the DIV with fresh data using JSON without repeating the same data over and over..
NightMICU
..but $.load() seems to be working okay. I'm going to try and learn more about JSON but I have a bit of a time constraint on this project at the moment, so I suppose I'll stay with $.load() for now -- unless someone can tell point me in the right direction for replacing all the data in the DIV via $.getJSON().Thanks again for your time and help, I did learn something today! :)
NightMICU
Yeah, I understood your point. I was just telling you the theoretical way of doing it. $.load() will work just fine, so if you're constrained in time, just go ahead and use it! There are ideal ways of solving our needs, and then the ones we do because of time constraints... $.load() is not bad at all, so stick to it and learn more about JSON, jQuery and JavaScript later! ;)
Seb
This is true! :)
NightMICU
+1  A: 

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.

Mailslut
Using `load()` means the server has to know how to render the results. IMHO, it'd be better to separate the presentation and leave the HTML part to the JavaScript side. After all, this HTML won't be used if JS is disabled.
Seb
^^ agreed......
Mailslut
Plus one since technically your solution would work for this application. Thanks :)
NightMICU