Skip to content
Advertisement

How to add a Countdown Timer with a value returned from Database using Ajax and displayed within a

Really stuck on this one. I have created an admin panel which retrieves data from MySQL database and displays the results within HTML using a Data table using Ajax/Json. This all works fine. One of the fields that is retrieved is a time which is given by the user in hours and minutes displayed as – 00:00. I need to take this time and make it countdown to zero within the tag. One other thing I should add is the page refreshes every minute as it needs to collect data often.

Can anyone help with this?

Here is the code so far HTML –

    <html> 
    <div class="table-responsive">
    <table class="display datatables" id="tableBody"></table>
    </div>                        
    </html>

And here is my Javascript –

    `$( document ).ready(function() {
$.ajax({
    url: 'php/fetch.php',
    mothod: 'post',
    dataType: 'json',
    success:function(data){
        let string = '';
                                        
        $.each(data, function(key, value){
            string += `<tr>
            <td>${value['timesubmit']}</td>
            </tr>`;
            string += `<tr>
            <td>: ${value['operatorname']}</td>
            </tr>`;
            string += `<tr>                
            <td># ${value['trucknumber']}</td>
            </tr>`;
            string += `<tr>                
            <td>${value['truckleaving']}</td>
            </tr>`;
            string += `<tr>
            <td>: ${value['jobstatus']}</td>
            </tr>`;
            string += `<tr>
            <td>${value['work']}</td>
             </tr>`;
            string += `<tr>
            <td>Time Left: ${value['typea9']}</td>  
             </tr>`;
        });
        

        $('#tableBody').append(string);
        $("#tableBody td:contains(Work: Yes New Job)").attr("style","background- 
        color:#44fa04");
        $("#tableBody td:contains(Work: No New Job)").attr("style","background- 
        color:#f80a26");
        $("#tableBody td:contains(Truck Leaving: Clean)").attr("style","background- 
        color:#288e04");
        $("#tableBody td:contains(Truck Leaving: Dirty)").attr("style","background- 
        color:#a07604");
        $("#tableBody td:contains(Truck Leaving: Unused)").attr("style","background- 
        color:#a5a39e");
    },
    error:{

    }
       });`

The ${value[‘typea9’]} is the value with the time in it which needs turning into a countdown.

Any help would be much appreciated with this.

Advertisement

Answer

Ok worked it out and here is the code if anyone else is ever stuck with a similar problem –

var displayHours;
var remainder;
var displayMinutes;
var displaySeconds;
var displayTime;
var timeInSeconds;
var truckNumber;


var displayHours1;
var remainder1;
var displayMinutes1;
var displaySeconds1;
var displayTime1;
var timeInSeconds1;
var truckNumber1;

displayTime = () => {
displayHours = Math.floor(timeInSeconds / (60 * 60));
remainder = timeInSeconds - (displayHours * 60 * 60);
displayMinutes = Math.floor(remainder / 60);
displaySeconds = remainder - (displayMinutes * 60);

if (timeInSeconds < 0) {
    document.getElementById("timer").innerHTML = "Time's up";
} else {
    document.getElementById("timer").innerHTML = displayHours + ":" + 
displayMinutes + ":" + displaySeconds;
}
};
window.onload = function() {
displayTime();
displayTime1();
};

interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
    clearInterval(interval);
    document.getElementById("timer").innerHTML = "Time's up";
    $('#tableBody').attr("style","background-color:#f80a26");
    window.sessionStorage.setItem('counter_key', 0);
} else {
    window.sessionStorage.setItem('counter_key', timeInSeconds);
}
}, 1000);
$( document ).ready(function() {

$.ajax({
    url: 'php/fetch.php',
    mothod: 'post',
    dataType: 'json',
    success:function(data){
        let string = '';
        $.each(data, function(key, value){
            
            string += `<tr>
            <td>${value['timesubmit']}</td>
            </tr>`;
            string += `<tr>
            <td>: ${value['operatorname']}</td>
            </tr>`;
            string += `<tr>                
            <td># ${value['trucknumber']}</td>
            </tr>`;
            string += `<tr>                
            <td>${value['truckleaving']}</td>
            </tr>`;
            string += `<tr>
            <td>: ${value['jobstatus']}</td>
            </tr>`;
            string += `<tr>
            <td>${value['work']}</td>
             </tr>`;
            string += `<tr><td>Time Left: <span id="timer"></span></td></tr>`;
        
            if(window.sessionStorage.getItem('timesubmit') === null) {
                window.sessionStorage.setItem('timesubmit', 
         value['timesubmit']);
            } else {
                if(value['timesubmit'] != 
         window.sessionStorage.getItem('timesubmit')) {
                    window.sessionStorage.removeItem('counter_key');
                    
         window.sessionStorage.setItem('timesubmit',value['timesubmit']);
                }
            }
            
            let time = value['typea9'];
            const myArray = time.split(":");
            
            console.log(myArray);
            
            var hours = 0;
            var minutes = 0;
            var seconds = 0;
            var interval = null;
            
            hours = parseInt(myArray[0]);
            minutes = parseInt(myArray[1]);
            
            if(window.sessionStorage.getItem('counter_key') === null || 
          window.sessionStorage.getItem('counter_key') === '') {
                timeInSeconds = (hours * 60 * 60) +(minutes * 60) + seconds;
            } else {
                timeInSeconds = window.sessionStorage.getItem('counter_key');
            }
        });
        
        $('#tableBody').append(string);
        $("#tableBody td:contains(Work: Yes New Job)").attr("style","background- 
        color:#44fa04");
        $("#tableBody td:contains(Work: No New Job)").attr("style","background- 
        color:#f80a26");
        $("#tableBody td:contains(Truck Leaving: 
        Clean)").attr("style","background-color:#288e04");
        $("#tableBody td:contains(Truck Leaving: 
        Dirty)").attr("style","background-color:#a07604");
        $("#tableBody td:contains(Truck Leaving: 
        Unused)").attr("style","background-color:#a5a39e");
    },
    error:{

    }
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement