I want to output the post id. But I am receieving null…
In footer.php
<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?
$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 passingpost_id
in your AJAX request, so I assume you want something like: