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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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');
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0