I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'cart_clb',
id : 1
},
method : 'POST',
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
And inside my functions.php
add_action( 'wp_ajax_post_cart_clb', 'cart_clb' );
add_action( 'wp_ajax_nopriv_post_cart_clb', 'cart_clb' );
function cart_clb(){
echo json_encode($_POST);
die();
}
As said above when i execute the request :
mydomain.com/wp-admin/admin-ajax.php 400 (Bad Request)
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Someone could help me to please? thank you.
First, use full and absolute url, with protocol (or at least protocol-independent form):
var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' }
Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}
, so in your case it should be:
data : {
action : 'post_cart_clb',
id : 1
},