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) {

    console.log(success);

}).fail(function(err) {
    console.log(arguments);
});

My functions.php

wp_register_script( 
    'fluent-js', 
    get_template_directory_uri() . '/assets/js/fluent-kit.full.min.js', 
    array(), 
    null, 
    true
);
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"));
    die();

}

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

up vote 3 down vote accepted

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.

  • 1
    Got there myself, but thanks for your effort :) – user3221 Apr 14 at 14:59

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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