reitermarkus
reitermarkus

Reputation: 708

How to get a cookie in php without refreshing the page?

I currently have this code and two problems:

I get the users timezone with Javascript and post it to the timezone.php via ajax, which sets a cookie with the users time. If the cookie is not set, say on first visit, the page would have to be refreshed in order to show the cookie value. I'm doing this with javascript at the moment, but there has to be another way. Also, since the page refreshes if there is no cookie, users with cookies disabled would get a refresh loop.

Any suggestions on how to solve these problems?

Thank you, Markus


index.php:

<!DOCTYPE html>
<html>
<head>
<style>
    .night {
        background: #000;
        color: #fff;
    }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<?php

        if(isset($_COOKIE["time"])) {
            $time = $_COOKIE["time"];
            if($time < 5.5 || $time > 19) {
                $night = true;
            }
        } else {
            echo("
            <script>
              var timezone = new Date().getTimezoneOffset()/60;

              $(document).ready(function() {
                $.post('timezone.php',{timezone: timezone}, function(data){location.reload(true)});
              });
            </script>
            ");
        }
?>

</head>
<body class="<?php echo $night ? "night" : "day"; ?>">
<?php if($night) {
    echo "It's nighttime! ($time)";
} else {
    echo "It's daytime! ($time)";
} ?>
</body>
</html>

timezone.php:

<?php

$timezone = $_POST["timezone"];

if(isset($timezone)) {
    date_default_timezone_set('Etc/GMT'.($timezone <= 0 ? '' : '+').$timezone);
    $time = date("G") + (date("i")/60);
    setcookie("time", $time);
}

?>

Upvotes: 0

Views: 4177

Answers (4)

Mr Jerry
Mr Jerry

Reputation: 1764

you can change index.php:

 $.post('timezone.php',{timezone: timezone}, function(data){ 
    if(data=='success'){
        location.reload(true)
    }
 });

and in timezone.php:

<?php

$timezone = $_POST["timezone"];

if(isset($timezone)) {
    date_default_timezone_set('Etc/GMT'.($timezone <= 0 ? '' : '+').$timezone);
    $time = date("G") + (date("i")/60);
    setcookie("time", $time);
    echo "success";
}

?>

Upvotes: 0

take
take

Reputation: 2222

You can use JQuery Plugin https://github.com/carhartl/jquery-cookie and check if the cookie is set in your $.post method like that

 $.post('timezone.php',{timezone: timezone}, function(data){
     if ($.cookie("time") != null) 
         location.reload(true);
});

Upvotes: 1

epascarello
epascarello

Reputation: 207527

set the class with JavaScript, there is no need for the server.

Upvotes: 1

GiantDuck
GiantDuck

Reputation: 1064

PHP script only runs when a request is made to the server. You could use JS and AJAX, or, if appropriate, an iframe.

Upvotes: 0

Related Questions