2

I have tried to set a cookie in an AJAX request, but it doesn't work the way its supposed to.

I found some valuable help on stack-overflow, but still, I can't get it to work properly.

I know there is many duplicate question ask before, but really I tried all of them.

The links below are the following answers that I've tried:

  1. Can an AJAX response set a cookie?
  2. Code Igniter Cookie
  3. Setting a cookie in an AJAX request?
  4. php setcookie not working with ajax call

This is the current code that I'm using:

$name = '_user';
$value = "hello";
$expire = time() + 86500;
$domain = '.localhost';
$path = '/';
setcookie($name,$value,$expire,$path,$domain);

These are the screenshots of inspect element it in Mozilla Firefox enter image description here and this one in Google Chrome enter image description here

Community
  • 1
  • 1
Codeiginiter
  • 99
  • 1
  • 12
  • 1
    Why not just setting the cookie using javascript or jQuery? once you get the response, set the cookie. Not saying that using PHP for the cookie is not a solution, but.. Well.. Just saying :) – briosheje Aug 06 '14 at 07:17
  • @briosheje but it is working with firefox, then why not with chrome? is there any restriction with chrome ? – Codeiginiter Aug 06 '14 at 07:32
  • usually not, as far as I know.. Perhaps you have some settings about the cookies in chrome? – briosheje Aug 06 '14 at 07:34
  • i am using the **CI** and it also set the cookie default when i call any controller of it with the `ci_session` name – Codeiginiter Aug 06 '14 at 07:38
  • When you get your response back from the server after the AJAX request is sent via javascript, if you refresh the page, either manually or through javascript, what happens? Does your page act like a cookie has been set? – j_allen_morris Aug 06 '14 at 07:40
  • @j_allen_morris i update question with the screenshot after ajax response and manually refreshing the page – Codeiginiter Aug 06 '14 at 07:44
  • Sorry. I know that I am able to use AJAX to allow my users to logout so it makes sense that logging in / setting a cookie would be possible but I've never tried it. I'll be following this to see the answers though. Good question. – j_allen_morris Aug 06 '14 at 07:46

1 Answers1

0

I had the same problem

I was doing this before

        $this->input->set_cookie('language', 'en');

and I was also doing this:

        $cookie = array(
            'name'   => 'language',
            'value'  => 'en',
        );
        $this->input->set_cookie($cookie);

Both did not work, and I tried giving it an expiration date and passing cookie in as an array

        $cookie = array(
            'name'   => 'language',
            'value'  => $this->session->userdata('language'),
            'expire' => '86500',
        );
        $this->input->set_cookie($cookie);

And, I got this to work...

juworld
  • 140
  • 1
  • 15