0

I have a page that once loaded the first time, gets updated via AJAX periodically (every few seconds). On the AJAX handling page I would like to update the user's cookie to reflect the "last visited time" (and thus mark data as read/unread). Is there anyway to use "setCookie" after the headers have been set? or must I resort to updating the cookie via JS?

Thanks!

R X
  • 281
  • 2
  • 11

2 Answers2

0

You need to prevent any output before setting cookies. Basically you could reoder the php commands or try to use ob_start to prevent outputs so you will be able to set cookies before you output any html.

rekire
  • 47,260
  • 30
  • 167
  • 264
0

One way could be to call php script with AJAX. You can make php script just for setting cookie. I did it this way:

HTML:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
    <script>
        function changeCookie(id)
        {
            data = 'id='+id;
            $.ajax({
                type: "POST",
                url: 'test.php',
                data: data,
                dataType: 'html'
                });
        }
    </script>
</body>

PHP:

<?php
    $id = $_POST['id'];
    setcookie("TestCookie", $id, time()+3600);  /* expire in 1 hour */
?>

Whenever you call changeCookie function, it will set your cookie to value you supplied in function's argument. You can modify this script to send name and expiry date to PHP script.

Another way could be without PHP, just plan javascript. You can find more about that here.