Trying to load content of a post via AJAX

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

So here is the functions.php part

Read More
    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?

Related posts

Leave a Reply

1 comment

  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');