Ajax success message returns HTML of my homepage

ajax, jquery, json, wordpress

Solution

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.

Problem

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...

Original source