Using ajax and wordpress (trying to do it properly). It is rather new to me but I had this working before with more flair. Seemingly-randomly started having issues so I broke my code down to the most basic level, and I can’t even get that to work!!! I feel like i’m just getting frustrated and it’s forcing me to miss a simple mistake. Is there anything wrong with this?
My jQuery:
$.post(
ajaxurl, // http://localhost/mysite/wp-admin/admin-ajax.php
{action: "post-save"},
function(response){
alert(response);
}
);
My PHP:
function update_post(){
echo json_encode(array("success" => "all systems go"), JSON_FORCE_OBJECT );
exit;
}
add_action( 'wp_ajax_post-save', 'update_post' );
The end result is the alert works, which means $.post is successful (right?), but the returned variable response
is the html source of my homepage…
I figured it out…
This might help some newbie like myself who makes the same mistake so I’ll answer my own question 🙂
Turns out I wasn’t logged in, go figure. The response was strange though and helped to throw me off, returning the entire homepage. The reason for this is I had blocked my functions files which includes the Ajax responder like so:
I should have known to log in (thought I was) but, such unexpected results and it was friday 🙂
Also note to anyone who stumbles onto this: if you do want someone to do ajax without being logged in use the no-priviledge version of wp_ajax, wp_ajax_nopriv.
In lieu of
The former does not require permission, ie being logged in, to do ajax requests.
I had the same problem, and the solution was to add the DOING_AJAX into the function
Although late, could help someone.
I had a
add_action( 'init', 'login_redirect' )
and which had awp_redirect
function on login. I added the( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX )
check before the redirect as @lenasterg mentioned and now the error is gone.