0

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);
?>
  • [Getting a cookie by name in JS](http://stackoverflow.com/questions/10730362/get-cookie-by-name) This may help you out. – dsadnick Mar 23 '17 at 21:57
  • @dsadnick I've had a look and the cookie isn't being created at all, the read function is operating normally – Ciaran Quigley Mar 23 '17 at 22:15

1 Answers1

0

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.

dsadnick
  • 624
  • 1
  • 7
  • 25