WordPress Ajax Refresh Div / Reload Content Without Refreshing the Page

WordPress Ajax Refresh Div / Reload Content Without Refreshing the Page

If you are looking to have some elements on the page reloaded in the background without refreshing an entire page, the code below is exactly what you’re looking for! And it actually works (many solutions I found online are either not working or are incomplete).

With this Ajax/Jquery code you can refresh certain div elements on the page and display new data to the visitors. (Ideal for comments, forms or any other dynamic sections of the site.)

Step #1. Go to your themes folder, wp-content > themes > yourthemename and open up functions.php file and place this code to the very bottom and save.

function ajaxdivrefresh() {

wp_enqueue_script(‘ajaxdivrefresh’, get_stylesheet_directory_uri() . “/js/ajaxrefresh.js”, array(‘jquery’));

}

add_action(‘wp_enqueue_scripts’, ‘ajaxdivrefresh’);

Step #2. In your theme directory root where functions.php is located, create an another folder and name it as js. Then create a Javascript file on your PC, add the code below and save the file as ajaxrefresh.js and upload it to newly created js folder.

jQuery('document').ready(function($){
setInterval(function() {

$(“.your-div-class-name”).load(window.location.href + ” .your-div-class-name”);

$(“#your-div-name”).load(window.location.href + ” #your-div-name”);

$(“#an-another-div”).load(window.location.href + ” #an-another-div”);

}, 7000);
});

As you can see in the code above, you can add any div class or ID and also set a refresh interval. 7000 interval is actually a 7 seconds reload time. 7000 milliseconds..

If you want to add more divs to the code, simply copy paste the line where your div code is and change the class or ID.

If for instance you want to automatically reload comments every 7 seconds, open up browser code inspector tool (right click) and find the class or ID for section where the comments are listed. Of course you won’t be using the main comment div container because in that case even the “Submit a comment” form would also be reloaded and no one would be able to leave a comment.

I do not suggest to use intervals lower than 5 seconds and also it’s not recommended to have too many (reload) divs on the website because this method may affect the server performance (it all depends on what server resources you have, how complex the website is, traffic etc.. up to 7,8 or even 10 div reload requests for shared hosting servers would be ok).