简体   繁体   中英

how can set cookie with Ajax/jQuery?

i have ajax function like below:

$.ajax({
url:"cookie.php",  
type: 'post',
data: {'ok': val},
success:function(data) {
alert(data);
}
});

and my cookie.php for setcookie is:

$name = "mySite";
$value = "stackoverflow.com";
setcookie($name, $value, time() + (86400 * 30), "/");
echo $name."=".$value;

with my ajax function mySite=stackoverflow.com show in my page but cookie not set in browser. why?

Cookies are set using the HTTP Set-Cookie header, sent in the HTTP response when a page first loads.

This header instructs the browser to store the cookie and send it back in future requests to the server.

When you set the cookie with ajax, the browser doesn't reload the current page, and no new headers are sent.
Instead, a new request is sent in the background with XMLHttpRequest , and the cookies are never added to the current page headers, as that page newer reloads and receives the header containing the cookie.

You have to reload the page and get a new set of headers to see the new cookies added in PHP.

There's also the option of setting the cookies in javascript, then they would be visible in the browser right away.

document.cookie="mySite=stackoverflow.com; expires=Thu, 18 Dec 2015 12:00:00 UTC; path=/";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM