Retrieve post in AJAX Callback

It’s possible to capture the $post_id using a combination of wp_get_referer() and url_to_postid() then reset the $post using setup_postdata.

That should work easy enough for the front-end. But on the admin side we’ll need to pull the query with parse_url and grab the ID using parse_str. For good measure we should double check if we’re editing a post by checking the action and also see if the ID is_numeric — running intval before we use it to rule out any funny business.

PHP

// for logged-in users
add_action( 'wp_ajax_foobar', 'wpse20160117_wp_ajax_foobar' );

// let's skip the nopriv because we want to only target logged-in users
// add_action( 'wp_ajax_nopriv_foobar', 'wpse20160117_wp_ajax_foobar' );

function wpse20160117_wp_ajax_foobar() {

    $url     = wp_get_referer();

    $post_id = '';

    // works with front-end urls
    // $post_id = url_to_postid( $url );

    if ( empty( $post_id ) ) { // lets do it the hard way

        // strip the query
        $query = parse_url( $url, PHP_URL_QUERY );

        // parse the query args
        $args  = array();
        parse_str( $query, $args );

        // make sure we are editing a post and that post ID is an INT
        if ( isset( $args[ 'post' ] ) && is_numeric( $args[ 'post' ] ) && isset( $args[ 'action' ] ) && $args [ 'action' ] === 'edit' ) {

            if ( $id = intval( $args[ 'post' ] ) ) {

                // cool.. it worked
                $post_id = $id;
            }
        }
    }

    if ( ! $post_id ) {
        echo "No foobar for you!";
    } else {
        global $post;

        // make sure we have a post
        if ( $post = get_post( $post_id ) ) {

            // prep the post data
            setup_postdata( $post );

            // now we're ready!
            echo "Are you referring to $post_id? Title: " . get_the_title();

        } else {
            echo "No post for you!";
        }
    }
    die();
}

JS

jQuery.post(
    ajaxurl, 
    {
        'action': 'foobar',
        'data':   'baz'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
);