Load random posts without refreshing page (jQuery)?

I’ve been playing with ajax for the past couple days – I like to go the hook route so first lets set up our ajax call:

$('#buttonID').click(function(){
    $.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'GET',
        data: {
            'action' : 'implement_ajax'
        },
        dataType: 'html'
    })
    .success(function(results){
        $('#ContentWrapper').html(results);
    })
    .fail(function( jqXHR, textStatus ) {
        console.log( "Request failed: " + textStatus );
    });
});

the action is what you want to call you ajax function – you can put this in the functions file:

function implement_ajax() {

    $ajaxQuery = new WP_Query(array('post_type' => 'post', 'posts_per_page' =>9, 'orderby' => 'rand'));

    ob_start();

    if($ajaxQuery->have_posts()) : 
        while($ajaxQuery->have_posts()) : $ajaxQuery->the_post(); 
    ?>

        <h1>Title: <?php the_title(); ?></h1>
        <?php /** Normal Loop Stuff **/ ?>

    <?php
        endwhile;
    endif;

    $htmlContent = ob_get_clean();
    echo $htmlContent;
    exit;
}
add_action('wp_ajax_nopriv_implement_ajax', 'implement_ajax');
add_action('wp_ajax_implement_ajax', 'implement_ajax');

We call ob_start to record everyting we echo out, all our html and variables so it doesn’t get returned back to our ajax call prematurely. Then we clean it all up via ob_get_clean() and return out html content to our ajax call where we can then just stick anywhere.

Once brought back you can put some fancy smancy fade in animation on it or whatever you need to make it look cool 😀 !