Proper way to load a single post via Ajax?

Here is my view: Load it inside your single.php why use ajax at all?
Google wont be able to see this (using most crawlers).

In any case – here is the right way to return the data…
please note that you can use get_post or wp_query. up tp you.

JS Part:

   jQuery(document).ready(function($) {
    $.post(ajax_object.ajaxurl, {
        action: 'my_load_ajax_content ',            
        post_id: post_id  // << should grab this from input...

    }, function(data) {

        var $response   =   $(data);
        var postdata    =   $response.filter('#postdata').html();

        $('.TARGETDIV').html(postdata);
    });
});

PHP Part:

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>';
}

add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );

Hope this helps.
again, i wouldnt recommend doing that but… this should work.

REVISION FOR GET POST ON CLICK

first: the button / link – should be something like

<button class="get_project" data-postid="POSTID HERE!">PROJECT NAME</button>

second: the js code listening to a click:

jQuery(function($){

    $('.get_project').click(function() {

        var postid = $(this).attr('data-postid');

        $.post(ajax_object.ajaxurl, {
            action: 'my_load_ajax_content ',            
            postid: postid
        }, function(data) {
            var $response   =   $(data);
            var postdata    =   $response.filter('#postdata').html();
            $('.TARGETDIV').html(postdata);
        });

    })

});

The php code needs no changing – just set the data you need.

Leave a Comment