Dan White Dan White - 5 months ago 36
PHP Question

Wordpress setcookie with AJAX

Firstly, I haven't seen any answers to similar questions that have sorted this. If you find one that already exists, please let me know.

Simple AJAX request that sets a cookie to store a timer expiry, the damn cookie isn't being set and I cannot work out why.

I'm using Vue Resource, so no jQuery please. In fact, I'm absolutely certain it has nothing to do with JS or the AJAX at all. It is posting fine and the "expiry" is being returned perfectly well.

The JS:

var sessionKey = document.querySelector('meta[name=dbs]').getAttribute('content');
if(sessionKey.length < 1){
var data = {action: 'dbs_reservation'};
this.$http.get(ajaxurl,data).then((response) => {
this.sessionExpiry = response.data.expiry;
})
}


The PHP

function dbs_timer_session(){
if(empty($_COOKIE['dbs_timer'])){
$t = time()+600;
setcookie('dbs_timer', md5($t).'|'.$t, COOKIEPATH, COOKIE_DOMAIN);
} else {
$t = explode('|',$_COOKIE['dbs_timer']);
$t = $t[1];
}
echo json_encode(['expiry' => $t]);
wp_die();
}


EDIT 1
As requested, the wp_ajax actions

add_action( 'wp_ajax_nopriv_dbs_reservation', 'dbs_timer_session' );
add_action( 'wp_ajax_dbs_reservation', 'dbs_timer_session' );

Answer

You were missing an argument for setcookie

 setcookie('dbs_timer', md5($t).'|'.$t, 'missing_expiry_time', COOKIEPATH, COOKIE_DOMAIN);
Comments