WooCommerce session data not preserved after multiple ajax calls

Viewed 202

I am trying to store a custom value to the WooCommerce session and have the data preserved over multiple ajax calls that I fire off in the Checkout screen.

This is the general flow of things:

  1. The user adds an item to their cart.
  2. The user goes to the checkout screen (with the item in their cart).
  3. I fire off an ajax call to do work on the server:
  • The ajax call:
jQuery.ajax({
    type : 'post',
    dataType : 'json',
    url : wc_add_to_cart_params.ajax_url,
    data : {
        action: 'update_cart'
    },
    success: function(response) {
        console.log('done storing data');
    }
});
  • The server code:
class SetCustomSessionData
{
    public function __construct()
    {
        add_action( 'wp_ajax_update_cart', [ $this, 'update_cart' ] );
        add_action( 'wp_ajax_nopriv_update_cart', [ $this, 'update_cart' ] );
        
        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
            WC()->session->set_customer_session_cookie( true );
        }
    }

    public function update_cart()
    {
        // update session data here
        WC()->session->set( 'my_custom_data_key_for_later', '123456789' );

        // my attempts to ensure that the value is actually saved
        WC()->session->save_data();
        WC()->cart->calculate_totals();
        WC()->cart->set_session();
        WC()->cart->maybe_set_cart_cookies();

        wp_die();
    }
}
  1. Then I make another ajax call to the retrieve the stored session value:
  • The ajax call:
jQuery.ajax({
    type : 'post',
    dataType : 'json',
    url : wc_add_to_cart_params.ajax_url,
    data : {
        action: 'get_cart_data'
    },
    success: function(response) {
        console.log(response);
    }
});
  • The server code:
class GetCustomSessionData
{
    public function __construct()
    {
        add_action( 'wp_ajax_get_cart_data', [ $this, 'get_cart_data' ] );
        add_action( 'wp_ajax_nopriv_get_cart_data', [ $this, 'get_cart_data' ] );
        
        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
            WC()->session->set_customer_session_cookie( true );
        }
    }

    public function get_cart_data()
    {
        echo WC()->session->get( 'my_custom_data_key_for_later' );

        wp_die();
    }
}
  1. It returns null instead of the value I stored previously.
0 Answers
Related