WooCommerce plugin – AJAX and $_SESSION issues

I’m trying to build a plugin that adds some custom data to a WooCommerce order.

Essentially I’m loading a specific product page from a custom button where I have a url variable set (&my_post_var={INTEGER}). This var is then processed in the product page, displaying some specific information available within WordPress, and is working as intended.

Read More

From hereon, after pressing Add to Cart, some of the custom data is pushed to the cart session. The AJAX jQuery and PHP callback are both correctly ran and the jQuery response is also correctly populated using PHP $_SESSION variable.

The issue is after that, when the Cart page displays, where the data displayed is the one from the previous &my_post_var={INTEGER} value, not the last value that was being passed.

I’m not using any cache plugins, this is a local development wordpress installation.

Can someone help me out pinpointing what might be wrong here?

This is the part of the code that is probably more pertinent:

function __construct() {

    // AJAX callback    
    function my_ajax_custom_data_callback_inline () {
        session_start();
        print_r ($_POST);

        write_log ( 'Data inside AJAX callback: ');
        write_log ( ' - DEBUG: _POST data: '. $_POST['my_post_data'][0] ); // This outputs the expected value

        $_SESSION['my_meta_data'] = $_POST['my_post_data'];
        print_r ($_SESSION);

        write_log ( ' - DEBUG: _SESSION DATA: ' . $_SESSION['my_meta_data'][0] ); // This outputs the expected value

        wp_die();
    }

    // AJAX hooks
    add_action('wp_ajax_' . 'my_custom_data', 'my_ajax_custom_data_callback_inline', 1);
    add_action('wp_ajax_nopriv_' . 'my_custom_data', 'my_ajax_custom_data_callback_inline', 1);


    if ( isset( $_SESSION['my_meta_data'] ) ) { // this is not being verified as TRUE

        add_filter( 'woocommerce_add_cart_item_data', 'my_add_cart_item_data', 10, 2 );

        add_filter( 'woocommerce_get_cart_item_from_session', 'my_get_cart_items_from_session', 10, 3 );

        add_filter( 'woocommerce_get_item_data', 'my_get_item_data',  10, 2 );

        add_action('woocommerce_add_order_item_meta', 'my_add_values_to_order_item_meta',10,2 );

        add_action('woocommerce_before_cart_item_quantity_zero', 'my_remove_user_custom_data',10,1 );

    }

}

Thank you very much

Related posts

1 comment

  1. I think that I found a way to sorting this, if it turns out unstable I’ll return to the question.

    Essentially I was making two different session_start() calls, one inside the ajax callback (as seen in the OP) and the other inside the woocommerce_add_cart_item_data filter function.

    Getting rid of both those calls and replacing them by a single call right after the __construct() starts makes it work as it should, even though I don’t know if there are any significant caveats with this.

Comments are closed.