I've been trying to implement the recommendation by @SagiveSEO in this thread: Proper way to load a single post via Ajax?
The idea: click a button and load a post via AJAX. The idea being that you'll have a tree of buttons to allow people to navigate quickly to useful content.
Unfortunately, it fails.
In the console I get the message "ReferenceError: ajax_object is not defined" which refers to the line "$.post(ajax_object.ajaxurl..."
What am I doing wrong?
Here's my HTML:
<button class="get_project" data-postid="3300">PROJECT NAME</button>
<div class="postcontainer"></div>
Here's my Javascript:
jQuery(function($){
$('.get_project').click(function() {
var postid = $(this).data('postid'); // Amended by @dingo_d
$.post(ajax_object.ajaxurl, {
action: 'my_load_ajax_content ',
postid: postid
}, function(data) {
var $response = $(data);
var postdata = $response.filter('#postdata').html();
$('.postcontainer').html(postdata);
});
})
//alert( "hello world" );
});
and here is the php from my functions.php file:
function my_load_ajax_content () {
$pid = intval($_POST['post_id']);
$the_query = new WP_Query(array('p' => $pid));
if ($the_query->have_posts()) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$data = '
<div class="post-container">
<div id="project-content">
<h1 class="entry-title">'.get_the_title().'</h1>
<div class="entry-content">'.get_the_content().'</div>
</div>
</div>
';
}
}
else {
echo '<div id="postdata">'.__('Didnt find anything', THEME_NAME).'</div>';
}
wp_reset_postdata();
echo '<div id="postdata">'.$data.'</div>';
}
// Next two lines corrected - thanks @dingo_d
add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );
Also required in functions.php within the script enqueuing function:
wp_enqueue_script( 'myajaxpostloader', get_template_directory_uri().'/js/ajax.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'myajaxpostloader', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
(note that my Javascript is saved as /js/ajax.js where /js/ is a subdirectory of the Wordpress theme).