0

I have a very basic validation script using PHP, and I want to set a cookie with jQuery Cookie plugin if they are validated. Being very new to PHP, I don't know how to code a Javascript function here:

if($validated) {
  //SET jQUERY COOKIE HERE: $.cookie('COOKIE_NAME', 'COOKIE_INFO', { expires: 1, path: '/' });)
  header("Location: correct.php");
} else {
  header("Location: incorrect.php");
}

I know I can use PHP for this, but later on I need to access the cookie in a jQuery function, and being far more familiar with client-side, I'd like it to be done using jQuery Cookie plugin.

Any guidance would be much appreciated!

air4x
  • 5,618
  • 1
  • 23
  • 36
JayDee
  • 1,633
  • 4
  • 21
  • 33
  • If you create it in php, JavaScript will be able to access it. There is no reason to do it with JavaScript in this context. – Kevin B Oct 29 '12 at 14:40
  • 1
    Did you know that setting Cookies is not a specific feature of jQuery? `jQuery.cookie` only provides a simple API for manipulating cookies at the client's side, it'll never becomer harder to read cookies using jQuery.cookie if the cookies are set on the server's side.. – Rob W Oct 29 '12 at 14:41
  • Didn't know jQuery could access server side cookies! – JayDee Oct 29 '12 at 14:41
  • Oh... I'd suggest you to feel the difference between server side and client side first. – VisioN Oct 29 '12 at 14:41
  • You will also want an exit or die after your header... – Lawrence Cherone Oct 29 '12 at 14:42
  • If you want to set/get local info with JavaScript/jQuery, localStorage and sessionStorage are much easier to work with than cookies, unless you have to be geriatric-browser compatible (http://www.html5rocks.com/en/features/storage) – st3inn Oct 29 '12 at 14:43

3 Answers3

2

I guess you are mixing concepts.

You can set a cookie in both server and client sides. And this cookie can be read by both parts again.

So you can set the cookie with PHP (http://php.net/manual/en/function.setcookie.php) and read it with jQuery (https://github.com/carhartl/jquery-cookie).

Hope it helps. Regards.

  • Thank you, I didn't know this could be done. This is why I love Stack Overflow, you learn new things everyday. Have now set it in PHP :) – JayDee Oct 29 '12 at 14:54
1

It could be done in JavaScript but there is no reason not to use PHP. The manual page is quite straightforward.

If you do implement it in JavaScript, simply break out into a regular page and include your script in the way you would usually. You'll need a window.location.href call in there to redirect after setting the cookie.

Community
  • 1
  • 1
bcmcfc
  • 25,966
  • 29
  • 109
  • 181
0

Please use google: PHP function

Syntax: bool setcookie ( $name , $value , $expire , $path );

BenMorel
  • 34,448
  • 50
  • 182
  • 322
androbin
  • 1,622
  • 14
  • 31