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?
If your javascript
action
is namedajaxify
, then these should be:the actions you hook are a concatenation of
wp_ajax_(nopriv_)
and youraction
name. the function that’s hooked to that action can have any name, so it could be: