I\'m trying to access a cookie\'s value (using $_COOKIE
) immediately after calling the setcookie()
function in PHP. When I do so, $_COOKIE[\
We can do this using AJAX calling.
If we want to create cookies on button click so first create a AJAX call for creating cookies then the success of first AJAX calling we can call another AJAX for getting the cookies.
function saveCookie() {
var base_url = $('#base_url').val();
var url = base_url + '/index/cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (data) {
if (data) {
var url = base_url + '/index/get_cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (response) {
var container = $('#show');
if (response) {
container.html(response);
}
}
});
}
}
});
}
<button type="button" onclick="saveCookie()">Save Cookie</button>
<div id="show"></div>
Using ob_start() and ob_flush() you can send the cookie to client and retrieve it in the same run time. Try this:
ob_start();
setcookie('uname', $uname, time() + 60 * 30);
ob_flush();
echo "Cookie value: " . $_COOKIE['uname'];
I set a constant at the same time the cookie was created
define('CONSTANT', true);
return setcookie('cookiename', 'cookie value goes here', time() + 60 * 60 * 24 * 30, '/');
I can then immediately do something by:
if(isset($_COOKIE['cookiename']) || $_COOKIE['cookiename'] || defined('CONSTANT') && CONSTANT)