Wordpress admin-ajax.php 404 bad request

2019-02-17 15:45发布

问题:

I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 404 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.

回答1:

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
},


回答2:

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}