javascript - php setcookie not working with ajax call -
i have page, test.php, following code:
<html> <body> <form> <script type="text/javascript"> function sendcookies(){ if (window.xmlhttprequest)/* code ie7+, firefox, chrome, opera, safari */ { xmlhttp=new xmlhttprequest(); } else /* code ie6, ie5 */ { xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status == 200) { alert('done'); } } xmlhttp.open("get", "/web/dev/classes/setcookie.php?time=" + new date()); xmlhttp.send(); } </script> <input type="text" id="txtinput" name="txtinput"/> <input type="button" id="btnsubmit" name="btnsubmit" value="submit" onclick="sendcookies()"/> <div id="divtest"> <?php if (isset($_cookie["testcookie"])) { echo $_cookie["testcookie"]; } else { echo "__results__"; } ?> </div> </form> </body> </html> i have page, setcookie.php, following code:
<?php $var = "this test"; setcookie("testcookie", $var, time()+60*60*24*30); ?> when test.php's button clicked, use xmlhttprequest call setcookie.php page. page executes, becuase if add echo it, in xmlhttp response. however, testcookie not seem getting set.
if in text.php, same command found in setcookie.php, cookie set accordingly browser sessions.
even after close / open browser, cookie remains unchanged when once set in test.php page manually.
----edit-----
i added:
if(!setcookie("testcookie", "a", time()+60*60*24*30, "/")) { echo "fail"; } to top of test.php, when reload page, never shows updated cookie... because cookie set without ,"/" parameter, , cannot modified later, ,"/" parameter.
after clearing cache , working suggested code, cleared cookies browser , used added parameter set method, able manipulate cookies pages!!! thank much!!
if don't add $path value setcookie(), defaults "the current directory". means if set cookie /web/dev/classes/setcookie.php, cookie gets set /web/dev/classes/, , above path won't see cookie.
to fix this, add specific $path setcookie. if app runs on domain root (example.com), use '/'. if it's in subfolder (example.com/myapp/), use '/myapp/'
setcookie("testcookie", $var, time()+60*60*24*30, '/');
Comments
Post a Comment