Trying to load content of a post via AJAX

The question:

OK I’m trying to load content of a post via AJAX.

So here is the functions.php part

    wp_localize_script('ajax-script', 'ajax_object', array('url' => $blogurl,'path' => $path,'ajaxurl' => admin_url( 'admin-ajax.php' )));
    add_action('wp_enqueue_scripts', 'javascripts');
    add_action('wp_ajax_ajax_action', 'ajaxify'); // ajax for logged in users
    add_action('wp_ajax_nopriv_ajax_action', 'ajaxify'); // ajax for not logged in users
    function ajaxify() {
        $post_id = $_POST['post_id'];
        $post_data = get_post($post_id);
        setup_postdata( $post );
        echo json_encode($post_data);
    }

and here is the jQuery part

$("a.ajaxed").click(function(event) {
    event.preventDefault();
    doAjaxRequest();
});
function doAjaxRequest(){
    jQuery.ajax({
        type: 'POST',
        url: ajax_object.ajaxurl,
        data: ({action : 'ajaxify',
            post_id: $(this).attr('id')
            }),
        dataType: 'JSON',
        success:function(data){
            console.log(data.post_title);
        }
    });
}

But when I look at the console it outputs 0, I don’t see the content. What am I missing?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

If your javascript action is named ajaxify, then these should be:

add_action('wp_ajax_ajaxify', 'ajaxify'); // ajax for logged in users
add_action('wp_ajax_nopriv_ajaxify', 'ajaxify'); // ajax for not logged in users

the actions you hook are a concatenation of wp_ajax_(nopriv_) and your action name. the function that’s hooked to that action can have any name, so it could be:

add_action('wp_ajax_ajaxify', 'some_random_function_name');
add_action('wp_ajax_nopriv_ajaxify', 'some_random_function_name');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment