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) {
function doAjaxRequest(){
        type: 'POST',
        url: ajax_object.ajaxurl,
        data: ({action : 'ajaxify',
            post_id: $(this).attr('id')
        dataType: 'JSON',

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

  • are you sure ajax_object.ajaxurl contains something? Try console.log(ajax_object.ajaxurl) before the jquery.ajax call, inside the doAjaxRequest function. – pixeline Aug 11 '12 at 22:33
  • Yes it's pointing to the wp-admin/admin-ajax.php file. – Gab Aug 12 '12 at 1:24

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');
  • OK it's corrected. But I still get a null response. I really don't know what to do :-/ – Gab Aug 12 '12 at 1:28
  • @Gab ok, the issue is post_id: $(this).attr('id'). you're no longer within the scope of your click function, so $(this) is undefined. pass the post id as an argument to your doAjaxRequest() – Milo Aug 12 '12 at 1:45
  • OK got it but still null response. – Gab Aug 12 '12 at 2:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.