Delay PHP execution until JavaScript cookie set?
Posted
by
Adam184
on Stack Overflow
See other posts from Stack Overflow
or by Adam184
Published on 2012-10-02T03:33:33Z
Indexed on
2012/10/02
3:37 UTC
Read the original article
Hit count: 163
php
|JavaScript
I am trying to delay PHP execution until a cookie is set through JavaScript. The code is below, I trimmed the createCookie
JavaScript function for simplicity (I've tested the function itself and it works).
<?php
if(!isset($_COOKIE["test"])) {
?>
<script type="text/javascript">
$(function() {
// createCookie script
createCookie("test", 1, 3600);
});
</script>
<?php
// Reload the page to ensure cookie was set
if(!isset($_COOKIE["test"])) {
header("Location: http://localhost/asdf.php/");
}
}
?>
At first I had no idea why this didn't work, however after using microtime()
I figured out that the PHP after the <script>
was executing before the jQuery ready function. I reduced my code significantly to show a simple version that is answerable, I am well aware that I am able to use setcookie()
in PHP, the requirements for the cookie are client-side.
I understand mixing PHP and JavaScript is incorrect, but any help on how to make this work (is there a PHP delay? - I tried sleep()
, didn't work and didn't think it would work, since the scripts would be delayed as well) would be greatly appreciated.
© Stack Overflow or respective owner