Getting a 404 error when using jQuery to post to W

2019-09-01 09:17发布

I have a plugin that registers to handle an ajax call (and the registration call is run, I checked it with logging). When I use jQuery to post to it (via admin-ajax.php), it is never called and Wordpress throws a 404 error. But, if I instead type into the address bar of the browser http://my-site.com/wp-admin/admin-ajax.php?action=my_ajax_function then it works!

client side

jQuery.post(
    {
        url: ajaxurl, //This is correct, I printed it out and it's "/wp-admin/admin-ajax.php"
        data: { action: 'my_ajax_function' },
        success: function(response)
        {
            //Never called
            console.dir( response );
        },
        dataType: "json"
    }
    //This is called
).fail( handleError );

Server Side

//This code IS called in my plugin's "load" hook
add_action( "wp_ajax_my_ajax_function", "handleAjax" );
add_action( "wp_ajax_nopriv_my_ajax_function", "handleAjax" );

//This is never called
public function handleAjax()
{
    echo "{ \"status\": \"ok\"}";
    die();
}

EDIT: When I post a form to ajaxurl directly, it works! It's only through jQuery that it throws 404! The below code executes perfectly:

//Posting without JQuery works!
form.method = "POST";
form.action = ajaxurl;
form.submit();

EDIT #2: The error appears to be with JQuery!

When I use Ajax directly (i.e. creating XMLHttpRequest in my code, calling xmlHttpRequest.open(...), etc), it posts perfectly! Only JQuery throws the error!

How do I find out what in JQuery is causing this?

2条回答
Rolldiameter
2楼-- · 2019-09-01 10:06

Try...

$.post(ajaxurl,data,function(resp){
  console.log(resp);
},'json').fail(handleError);
查看更多
疯言疯语
3楼-- · 2019-09-01 10:23

you misunderstood $.ajax and $.post, use this instead

jQuery.ajax({
        url: ajaxurl,
        type : 'post',
        data: { action: 'my_ajax_function' },
        success: function(response){
            console.dir( response );
        },
        dataType: "json"
}).fail( handleError );

$.post is a short hand of $.ajax for type post, which having following signature

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
查看更多
登录 后发表回答