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?
Try...
you misunderstood $.ajax and $.post, use this instead
$.post is a short hand of $.ajax for type post, which having following signature