I am trying AJAX post request with no avail. I tried a lot of answers here in the matter already, including localizing admin-ajax scripts, adding action to the data field, providing headers, providing priv and no_priv hooks.

I am pretty sure, that it is some stupid little mistake, but it takes much longer than it should already. I appreciate your help.

My javascript:

var variation = { name: 'personal', id: '467' };
var options   = {
    url : WC_VARIATION_ADD_TO_CART.ajax_url,
    method: "POST",
    contentType: 'application/json', // tried without it too
    dataType: 'json', // tried without it too
    data: {
        "action"        : "woocommerce_add_variation_to_cart",
        "product_id"    : "466",
        "quantity"      : 1,
        "variation_name": variation.name,
        "variation_id"  : variation.id,

options.data = JSON.stringify(options.data);

$.ajax(options).done(function(success) {


}).fail(function(err) {

My functions.php

    get_template_directory_uri() . '/assets/js/fluent-kit.full.min.js', 
wp_enqueue_script( 'fluent-js');
$vars = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'fluent-js', 'WC_VARIATION_ADD_TO_CART', $vars );

function woocommerce_add_variation_to_cart() {

    echo json_encode(array("msg" => "Good"));


add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'woocommerce_add_variation_to_cart' );
add_action( 'wp_ajax_woocommerce_add_variation_to_cart', 'woocommerce_add_variation_to_cart' );

My DevTools / Network tab:

enter image description here


I tested your code and got it to work by removing the following line as it is unnessacary.

options.data = JSON.stringify(options.data);

You can also safely remove the following lines in your AJAX call.

contentType: 'application/json', // tried without it too
dataType: 'json', // tried without it too

Please check out AJAX in Plugins on the WordPress Codex for more info.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.