I'm trying to set a cookie within an AJAX call after I get the response of an API. The API and AJAX call are working fine, but the cookie is not being set.
I used the 'COOKIEPATH' and 'COOKIE_DOMAIN' constant of WordPress, as described in this post: https://stackoverflow.com/a/8531421/4638682 but this does not seem to do anything. What am I doing wrong? Here's my AJAX call:
function run_zipcodecheck()
{
if (empty($_POST['zipcode'])) {
exit;
}
$zipcode = str_replace(' ', '', $_POST['zipcode']);
$link = 'https://import-nl.eflorist.net/api/CheckDelivery?pc=' . $zipcode . '&kd=0';
$deliverytoday = get_api_data($link);
$args = [];
if (!empty($deliverytoday) && ($deliverytoday == '"1"' or $deliverytoday == '1')) {
$type = 'success';
$args['title'] = __("You can get flowers delivered today if you're quick!", 'qore');
$args['close'] = 'false';
$args['class'] = 'my-6';
$cookieVal = '1';
} else {
$type = 'warning';
$args['title'] = __("Unfortunately, delivery of bouquets is no longer possible for today.", 'qore');
$args['close'] = 'false';
$args['class'] = 'my-6';
$cookieVal = '0';
}
setcookie('user-zipcode', $zipcode, MONTH_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
setcookie('delivery-today', $cookieVal, DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
get_template_part('includes/components/alert', $type, $args);
wp_die();
}
The 'get_api_data' is simply a wp_remote_get function with some error handles, but is working fine.
Hope you guys can help me out.
else
case or default value for$cookieVal
as it's only defined inside 2 if statements, but if neither of those are true then it not only has no value but it doesn't exist. Have you confirmed that this is not the case? This scenario could even be interpreted as unsetting the cookie, and should have been flagged by tooling such as PHPCS/PHPMD/etc due to using a potentialy undefined variablereturn
in it, which is incorrect, it needs to exitexit;
indeed. Also editted the code so it has an else instead of an elseif. But my mean issue is still that the cookie is not being set. Do you have any idea why this happens?