How to set transients with ajax?

Hi. I’m fairly new to wordpress and coding in general. So bear with me.

I want to set some transients to prepopulate woocommerce order forms, and to manually set the shopping cart content. The inputs for the transients come from a modified calendar booking plugin which is heavily reliant on ajax. The idea is to grab the field contents from the plugin with jquery, set them as transients, and then use a filter in functions.php to set the field values on the woocommerce checkout page.

The problem is that I can’t seem to figure out how to set those transients in either a separate php file, or a function inside functions.php. If I use php sessions, everything works, but I don’t really want to do that.

Here’s my code atm.

Functions.php:

function set_thetransients() {
        set_transient('myValue', $_POST['sent_myValue']);
        /* Bunch of other variables set with the $_POST method */
        wp_die();  
    }

add_action( 'wp_ajax_nopriv_set_thetransients', 'set_thetransients' );
add_action( 'wp_ajax_set_thetransients', 'set_thetransients' );

add_filter('woocommerce_checkout_get_value', function($input, $key ) {
    global $current_user;
    switch ($key) :
        case 'billing_first_name':
            return $current_user = get_transient('myValue');
        break;
	/ * Bunch of other fields get set the same way */
    endswitch;
}, 10, 2);

Within the booking calendar js file, when submitting the form:

var ajaxurl = '/Site folder name/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, {sent_myValue: $("#form_field_id").val() 
/* Bunch of other fields grabbed with jQuery */   });



Source link