简体   繁体   中英

PHP Accessing cookie value in html page using jquery+ajax

I'm trying to access cookie value into html using jquery or ajax ,I'm new to ajax so I don't know how to access json values. I tried with $.getJSON() but it not working. When I execute same code into localhost , it showing john .

test.php

<?php
    $cookie_name = "user";
    $cookie_value = "john";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    echo json_encode($_COOKIE[$cookie_name]);
?>

Not sure how you are planning on using the value on the client side, but the issue as to why you are not getting output is the fourth parameter option you have in setcookie() function. I'm not sure why you have this as the documentation I found does not list a fourth option. The function accepts the name, value, and time to live.

Also, if all you want to do is return the name of the user value, you don't need to use json_encode(). You can simply echo the name as the response:

<?php

     $cookie_name = "user";
     $cookie_value = "john";
     setcookie($cookie_name, $cookie_value, time() + (86400 * 30));

     echo $_COOKIE[$cookie_name];

?>

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