2

I've created a page that sets a cookie on the click of a button(ajax with PHP) and then redirects to a different page (JavaScript).

$.ajax({
   url: "addTeacher.php",
   dataType: 'html',
   data: text,
   cache: false,
   type: "GET",
   success: function(html) {                                                        

      window.location = "teacherList.php";
   }
});

But when I try to access the set cookie in the page that is being redirected to(teacherList.php) it is empty. If refresh the redirected page once more, then the cookie is accessible.

This is how I set the cookie in addTeacher.php.

addTeacher($teacher, $items);    
setcookie("$teacher_id", "$teacher_id", time() + (86400 * 1), "/");
  • make sure nothing is being output before your cookie in the header. Also why do you have quotes around your variables? just curious – Rotimi May 03 '17 at 12:23
  • I think you need to use setcookie('teacher_id', $teacher_id, time() + ...... Otherwise its a bit difficult to fetch the cookie later on – Scriptman May 03 '17 at 12:28

2 Answers2

2

You have to send asynchronous request of ajax so that after completion of ajax request you have the cookie set by you.Hope you will got it.Thanks

Waqas Ahmed
  • 185
  • 2
  • 11
0

It turns out that setting the Path option is important when sending cookies in an AJAX request. If you set Path=/, e.g.:

Set-Cookie:SessionId=foo; Path=/; HttpOnly

Please refer this: Setting cookies in an ajax request

Community
  • 1
  • 1
informer
  • 821
  • 6
  • 18