Ryan D
Ryan D

Reputation: 751

how to refresh div without refreshing all php data

I would think this is simple but cannot figure it out for the life of me.. I want to refresh a div without refreshing everything.. I have a timer on each image that counts down from 24 hrs to 0 then disappears.. it all works but I cant seem to just refresh the timer div..

My php -

$date = date('Y-m-d H:i:s');

$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $path = $row['path'];
    $user = $row['user'];
    $update = $row['update_date'];

    $timeFirst  = strtotime($date);
    $timeSecond = strtotime($update);
    $timeSecond = $timeSecond + 86400;
    $timer = $timeSecond - $timeFirst;

if($timer <= 0){

}else{
    echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
    echo '<div id="user">#'.$user.'</div>';
    echo '<div id="timer">'.$timer.' </div>';

    }
  }
}

I would like to refresh just the timer at 1 second intervals not the images.. I know I can use ajax to call it from an external file that loads all the content also as far as I know..Still new at this. *side not this is chopped up code for the example not all of it.

Upvotes: 0

Views: 597

Answers (2)

Nikola R.
Nikola R.

Reputation: 1173

As per my comment, you could do something like this:

  1. Add class "timer" to your #timer element (if you have more than one #timer element, use different ID for each element).
  2. Create php script which returns new $timer whenever it's called:

ajax-timer.php

<?php

/* include file where $conn is defined */


$response = array();

$date = date('Y-m-d H:i:s');

$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $update = $row['update_date'];

        $timeFirst  = strtotime($date);
        $timeSecond = strtotime($update);
        $timeSecond = $timeSecond + 86400;
        $timer = $timeSecond - $timeFirst;


        if($timer > 0) {
            //Add just timer to response array
            $response[] = $timer;
        }
    }
}

//Return json response and handle it later in ajax:
echo json_encode(array(
    'result'=>empty($response) ? 0 : 1,
    'data'=>$response));
die();
  1. Request data from ajax-timer.php with $.ajax and populate data when response is received:

timer-update.js

var ajaxTimerThread = 0;
var ajaxTimerRunning = false;

function ajaxTimerRun() {
    //Prevent running function more than once at a time.
    if(ajaxTimerRunning)
        return;

    ajaxTimerRunning = true;
    $.post('ajax-timer.php', {}, function (response) {
        ajaxTimerRunning = false;
        try {
            //Try to parse JSON response
            response = $.parseJSON(response);
            if (response.result == 1) {
                //We got timer data in response.data.
                for(var i = 0; i < response.data.length; i++) {
                    var $timer = $('.timer').eq(i);
                    if($timer.length) {
                        $timer.html(response.data[i]);
                    }
                }
            }
            else {
                //Request was successful, but there's no timer data found.
                //do nothing
            }
            //Run again
            ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
        }
        catch (ex) {
            //Could not parse JSON? Something's wrong:
            console.log(ex);
        }
    });
}

$(document).ready(function() {
    // Start update on page load.
    ajaxTimerRun();
})

Upvotes: 1

Abela
Abela

Reputation: 1233

Toss your existing php code into a separate .php file

Then use a jquery method called load() to load that php file into your div.

$(document).ready(function() {
    $("#div_ID_you_want_to_load_into").load("your_php_file.php");
    var pollFrequency = function() {
        if (document.hidden) {
            return;
        }
        $("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
    };
    setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});

Now, within this code above is something is not needed, but can be helpful, and that is the if (document.hidden) {return;} which is basically a command to the browser that if the browser tab is not in-focus do not fire off the setInterval poll.

Also a good idea to keep in the randval= math stuff, just to make sure there is no caching.

Upvotes: 0

Related Questions