Ajax simple experiment

I want to output the post id. But I am receieving null…

In footer.php

Read More
<script>
jQuery("a.more-link").live('click', function(event) {
    event.preventDefault();
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'POST',
        data: {
            'action' : 'do_ajax',
            'post_id' : '<? echo $_REQUEST['post_id'];?>'
        },
        dataType: "json",
        success: function(myResult) {
            alert(myResult);
        },
        error: function(error) {
            alert(error);
        }
    });
});
</script>

And in functions.php

add_action('wp_ajax_nopriv_do_ajax', 'retrieve_id');
add_action('wp_ajax_do_ajax', 'retrieve_id');

function retrieve_id(){      
    global $post;
    $myPost= $post->ID;
    $output =  $myPost;
    $output = json_encode($output);
    if (is_array($output)) {
        print_r($output);
    } else {
        echo $output;
    }
    die;
};

Why does it show null?

Related posts

1 comment

  1. $post isn’t set in your AJAX handler, it doesn’t exist. An AJAX request is a separate request from the one that rendered the page you’re making the request from, php data doesn’t persist across these two requests. You’re passing post_id in your AJAX request, so I assume you want something like:

    function retrieve_id(){
        echo $_POST['post_id'];     
        die;
    }
    

Comments are closed.