sasori
sasori

Reputation: 5455

how to auto redirect a page based on given time? should i use javascript ? how?

let's say i have this code

$itemtoDisplayTime = $model->getItemTime()  // e.g 03:00pm
$currentTime = date('H:i'); //this is the system clock/time

is it appropriate to use javascript to automate the process of redirection without having to refresh the page ? if so, how ?

let's say the $itemDisplayTime is now equal to $currentTime , how to use these variables in javascript or jquery if possible

Upvotes: 0

Views: 717

Answers (3)

Devon Bernard
Devon Bernard

Reputation: 2300

Depending on what your goal is I would say there are two possible solutions.

If you want to refresh a page to do database tasks I would suggest cron-jobs if your host supports it. Because then you can have your computer shut off and the tasks run server-side all by themselves one example of that would be: (The time is chosen on your hosts website)

php -q /home/path_to_file/your_link.php >/dev/null 2>&1 

If this is for some other purpose and you would have to use ajax; because if you use getItemTime I think it would just get it once when the page first loads, you would need to keep making calls every few minutes to re-execute the java-function and re-check the time but that would get into a lot more complicated of a solution. If you would like to try this way please explain more thoroughly what the task in mind you are trying to do so I can make specific code.

Upvotes: 0

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

First calculate after how many seconds it should redirect. Then use the seconds in the following methods.

For your case strtotime might work.

$seconds = strtotime($itemtoDisplayTime) - time();

There are several ways to redirect,

  1. Send a Refresh header from PHP.

    header("Refresh: $seconds; url=$url");
    
  2. Using Javascript

    window.setTimeout(function(){
        location.href="desired url";
    }, seconds*1000);
    

Upvotes: 2

Sibu
Sibu

Reputation: 4617

Why do you want to use javascript, when you can use php to do this, Try this way

if($itemDisplayTime==$currentTime)
header( "refresh:0;url=yourpage.php" );

Upvotes: 0

Related Questions