0

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' );
ggdx
  • 3,024
  • 4
  • 32
  • 48
  • Who voted to close and phantom downvoter? Would you mind explaining why? – ggdx Jun 27 '16 at 19:45
  • +1 for not using jQuery. You seem to passing `COOKIEPATH` into the expiry time argument. For testing you should be passing back the output from setcookie which would be false. I assume you know you can set cookies with js as well? A lot quicker ! – David Jun 27 '16 at 22:12
  • Thanks David! Can't believe I missed that! Please make this an answer and I'll mark as the correct one – ggdx Jun 27 '16 at 22:16
  • no problem, ajax testing can be a pain when dealing with json output...but has to be done :( – David Jun 27 '16 at 22:20

2 Answers2

3

You were missing an argument for setcookie

 setcookie('dbs_timer', md5($t).'|'.$t, 'missing_expiry_time', COOKIEPATH, COOKIE_DOMAIN);
David
  • 5,897
  • 3
  • 24
  • 43
-1

Can you show us how you are setting the action? Below are the samples depending on if you are in the admin or frontend.

//For admin use only:
add_action( 'wp_ajax_my_action', 'my_action_callback' );

//For front end use
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
Fencer04
  • 1,084
  • 1
  • 11
  • 17
  • It's not that, the AJAX request is sort of successful and the JSON is correctly being returned. Either way, I have edited the question – ggdx Jun 27 '16 at 19:46