Let us assume that you already have a Product Variation in WooCommerce and a Custom Form where you put all the data needed before adding a Custom Product to cart.

1. Copy this code and paste on your enqueued .js file:

$('body').on('submit', '#your-form-id-here', function( e ){




        e.preventDefault();

        const currElem = $(this);

        let myData        = currElem.serializeArray();




        $.ajax({

                url : wpccAJAXHanlder.ajaxurl,

                type : 'post',

                data : {

                    action    : 'add_to_cart_action',

                    myData : myData

                },

                beforeSend:function(){

                    // do stuff here

                },

                success : function( response ) {

                    console.log(response);

                    // do additional stuff here

                }

        });

});

Here, you can see that we prevented the form submission using e.preventDefault().  After that, we serialized the form data and pass it to ajax in order to send it to our handler which is going to be the next part.

2. Copy this code and paste it on your .php file:

function wpccustom_checkout_on_form_submit(){

global $wpcargo, $woocommerce;

parse_str( $_POST[‘myData’], $array );

// Checked if the woocommerce is Enable – Create Product Order

if( is_wpcsr_woocommerce_enable() ){

$product_variation  =  array(

‘product_id’           => $array[‘product_id’],

‘product_name’     => $array[‘product_name’],

‘product_price’      => $array[‘product_price’],

‘product_quantity’ => $array[‘product_quantity’],

// you can add as many data as you can here

);

$add = $woocommerce->cart->add_to_cart( $your_product_variation_here, 1, 0, array(), array( ‘_myProduct’ => $product_variation ) );

if ($add) {

echo ‘success;

wp_die();

}

}

}

add_action( ‘wp_ajax_nopriv_wpccustom_checkout’, ‘wpccustom_checkout_on_form_submit’ );

add_action( ‘wp_ajax_wpccustom_checkout’, ‘wpccustom_checkout_on_form_submit’ );

Here on our ajax handler, we grabbed the data by $_POST[‘myData’] then we parsed it and formatted as array. After that, we created a new order from the product variation and added it to cart.