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( $ ) {
In Vanilla JavaScript You get a Bad Request if You don't append this header to the POST request:
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
So please be sure that jQuery appends as well that header.
In my case, I am using Class based approach. And I found the issue was because I was using wp_ajax_ request in constructor.
If you are using ajax methods inside class, move wp_ajax_ handles outside of class (write in main plugin file) and pass classname and method name. For example:
add_action( 'wp_ajax_your_handle', [ 'Class_Name', 'function_name' ] );
add_action( 'wp_ajax_nopriv_your_handle', [ 'Class_Name', 'function_name' ] );
I have modified your code and look at this :
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'post_cart_clb',
id : 1
},
method : 'POST', //Post method
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
This is the syntax of WordPress ajax : wp_ajax_{Your_action_name} wp_ajax_nopriv_{Your_action_name}
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
},