'Ajax success message returns HTML of my homepage
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...
Solution 1:[1]
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:
function block_users()
{
if( !current_user_can( 'delete_pages' ) ) {
wp_redirect( get_home_url(), 301 );
exit;
}
}
add_action('admin_init','block_users');
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.
add_action( 'wp_ajax_nopriv_action', 'function' );
In lieu of
add_action( 'wp_ajax_action', 'function' );
The former does not require permission, ie being logged in, to do ajax requests.
Solution 2:[2]
I had the same problem, and the solution was to add the DOING_AJAX into the function
function block_users()
{
if( !current_user_can( 'delete_pages' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
wp_redirect( get_home_url(), 301 );
exit;
}
}
add_action('admin_init','block_users');
Solution 3:[3]
Although late, could help someone.
I had a add_action( 'init', 'login_redirect' ) and which had a wp_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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jamil |
| Solution 2 | lenasterg |
| Solution 3 | Maklas |
