Load post content into div with ajax

You are asking to load the next page but it doesn’t make sense to load the entire page if all you want is the image. The following will do just that.

The HTML

At a minimum add a wrapper div to isolate the image we want to replace and so it’s possible to search in our ajax response for the new image we want to use to replace the current one.

<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/2/"><img src="blah1.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/3/"><img src="blahab.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/4/"><img src="blahco.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/5/"><img src="blahneat.jpg" alt=""/></a></div>

The Javascript

This should be placed in your existing $(document).ready(function(){ ... }); function

$('body').on('click', '.image-wrap', function(e) { // listen for 'click' on our '.image-wrap' element
  e.preventDefault();  // Prevents default behavior on the a element

  $.ajax({

    url: $(this).find( 'a' ).attr( 'href' ), // the url we are fetching by ajax
    success: function (response) {

      newImg = $(response).find('.image-wrap').html(), // get the new href link and image from the response, contained in div.image-wrap

      $( 'div.image-wrap' ).html( newImg ); // set the new html for our inner div

    }
  }).fail(function (data) {

    if ( window.console && window.console.log ) {

      console.log( data );  // log failure to console

    }

  });

});

EDIT

to add a script via wp_enqueue_script just add this to your functions.php

add_action( 'wp_enqueue_scripts' 'my_custom_js');
function my_custom_js(){
  wp_enqueue_script( 'main-js', get_stylesheet_directory_uri() . '/js/main.js' , array( 'jquery' ), '1.0.0', true );
}

then in your themes folder create a file main.js in a js folder and then add to it the javascript code above. the file should be located in theme_folder/js/main.js and the above script should be loaded in document ready

$(document).ready(function(){
  // Script
});

the parameters of the wp_enqueue_script function are as follow

  • Param 1: script handle. should be a unique name and is used to identify the script you are loading. For instance, if you need to deregister the script you would call wp_dequeue_script and use this handle.
  • Param 2: the location of the file you are loading
  • Param 3: an array of dependencies for this file (files that should be loaded before, here we require jQuery
  • Param 4: a version for this file (optional)
  • Param 5: should the script be loaded at the begining of the page or just before the closing </body> tag. true means before the closing </body> tag. Default false

Leave a Comment