samedi 25 avril 2015

jQuery time display with AJAX requests


I'm building a webpage that retrieves data from a server using AJAX. I'm looking to display time in a div (in hours/minutes/seconds, like 10:45:30, with leading zeroes). One of my AJAX calls is run very infrequently; roughly 45 minutes or so between each call. The call in question gets a JSON string with the server's current time (via PHP). I'm able to get this string with the hours, minutes, and seconds separated or as one item.

I've seen a lot of timer functions that use setInterval and JS functions to get the current time; these operate client-side/locally. I've also seen functions that will ask for the server's time every minute (which seems much too frequent).

What I would like to do is grab the server's time from the AJAX call (which I can assign to variables; this part I have figured out)., and let a timer function use the variables from that call as a starting point to increment the seconds, minutes, etc.

Here's an idea of what this may look like; first, the AJAX call that gets the time variables.

function askTime(){
        $.ajax({
                url: "servertime.php",
                dataType: "json",
                cache: false,
                success: function(data) {
                    timeHours = (data.timeHours);
                    timeMinutes = (data.timeMinutes);
                    timeSeconds = (data.timeSeconds);
                    timerFunction();

                },
            });
    }

And then on the success of that call, run the function that would display the time in a div of a certain id, like $('#timeDisplay).html(timestring) .

So, shortly: how can I use jQuery to display time using infrequent AJAX calls to server time?


Aucun commentaire:

Enregistrer un commentaire