Refresh Only A Piece Of Webpage With AJAX

March 4, 2015

I was working on a new project when I had come up with a certain scenario. What I needed to do was refresh a piece of the webpage after an action was taken. Using jQuery, it’s normally pretty straight forward, but it wasn’t working as exactly the way I needed it.

Here is what you would normally use when you use AJAX to get a piece of a webpage.

  
$('.container').load('page.html .container');
  

This works great in most instances, but because I was using Bootstrap, and the container I needed was also using the grid system, it became all wonky. What I discovered is that you can go deeper with your selectors. This is what I changed it too.

  
$('.container').load('page.html .container > *');
  

With this new snippet, I can load all on my content without doubling up the .container. You can see a side-by-side comparison on CodePen. Who really wants container inception, anyways.

I actually took it a step further and made a little function of it that you could easily add into your project.

  
function refreshPagePiece( url, container, callback ) {
 $(container).load( url +' '+ container +' > *', function() {
    if ( callback )
       callback();
 } );
}
  

This is a quick and simple way to grab a fresh piece of content from your website without reloading the whole page.

Enjoy

Comments are closed