Setting a cookie in an AJAX request? Setting a cookie in an AJAX request? ajax ajax

Setting a cookie in an AJAX request?


Here are few suggestions:

  • Make sure that you are specifying the correct expiration format of date
  • When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....'); eg:

    header('Location: http://www.example.com/');setcookie('asite', $site, time()+60*60, '/', 'site.com');

  • If you have human urls like www.domain.com/path1/path2/, then you must set cookie path to / to work for all paths, not just current one.

    setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');

Notice the last / in the arguments.

From PHP manual:

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

  • setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script meaning there should be no html/code echo statements before that.


You won't be able to set the cookie server-side when using an AJAX call. Instead, wait until you get a successful response and set the cookie client side. To make it easier, you could use a jQuery plugin.