简体   繁体   中英

How do I get a cookie from PHP to javascript?

I'm having trouble getting a non-null response from my readcookie function in Javascript. Ideally I would get a boolean response as to whether an id exists in my database or not, but currently it's only coming up with null. I've had a look into the stored cookies and the IDFound cookie is not stored at all.

Javascript side:

function readCookie(name) {
    $.get("/test/phpServerGet.php","function(result){}")
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0){ console.log("found")
        return c.substring(nameEQ.length,c.length)};
    }
    return null;
}

PHP:

<?php
require_once 'path_to_db_connect.php';
$id_exists = false;
$CollegeID = $_COOKIE["CollegeID"];
echo $CollegeID;
$request = $connect->prepare("SELECT `CollegeID` FROM `users` WHERE `CollegeID` = ?;");
$request->execute(array($CollegeID));
$result = $request->fetch(PDO::FETCH_ASSOC);
$cookie_name = "IDFound";
if ($result['CollegeID'] == $CollegeID)
{   echo "YES";
        $id_exists = true;
}

else if ($result['CollegeID'] != $CollegeID)
{
        $id_exists = false;
}
setcookie($cookie_name, $id_exists, 1000);
?>

PHP set cookie

setcookie($cookie_name, $id_exists, 1000);

the 3 argument is set to 1000, try replacing that with

time() + 60 
setcookie($cookie_name, $id_exists, time() + 60);

That should give the browser more time to find the cookie and parse it. time() + 60 will be one min.

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