Explain Codes LogoExplain Codes Logo

Refresh/reload the content in Div using jquery/ajax

javascript
ajax
jquery
promises
Alex KataevbyAlex Kataev·Oct 26, 2024
TLDR

To refresh content inside a div, use jQuery's .load() method, fetch updated HTML from a server endpoint, and inject it into selected div. Here's the crux:

$("#divId").load("endpoint.php"); // Instant refresh

Or for periodic updates, use the setInterval function:

// 5-second refresh presented with love from setInterval setInterval(() => $('#divId').load('endpoint.php #content'), 5000);

This snippet refreshes #divId every 5 seconds with data from endpoint.php. #content specifies only the #content section of endpoint.php should be loaded, reducing redundant data transfer.

Select the right element

Make sure the selector ID targets the intended div. Incorrect use can lead to a mini inception:

$("#mydiv").load(location.href + " #mydiv"); // Div-ception if not done carefully

Avoid div inception and save your page from unwanted nesting:

$("#mydiv").load(location.href+" #myDiv>*","");

Let the user know with an indicator

Implement a loading indicator to provide visual feedback:

$('#mydiv').html('<div class="loader">Loading...</div>').load('endpoint.php');

Then, ensure the callback in .load() hides the loader:

$('#mydiv').load('endpoint.php', () => $('.loader').hide()); // Hide and seek champion: Loader

Use Ajax when dealing with forms

When working with forms, serialize data for Ajax POST requests:

$.ajax({ type: 'POST', url: $('#myForm').attr('action'), data: $('#myForm').serialize(), success: function(response) { $('#myDiv').html(response); } }); // Do you even POST, bro?

Implement a .submit() event handler for form submission.

Doing more with Ajax

Error handling in Ajax

Keep some .fail() guards to catch pesky errors:

$('#myDiv').load('endpoint.php').fail(function() { alert('Error loading content!'); // Oops! The internet ate my request });

Using animations

Enhance UX with animation on content refresh. Let your div play peekaboo:

$('#myDiv').fadeOut().load('endpoint.php #myDiv', function() { $(this).fadeIn(); //Div: Now you see me, now you don't, now you do! });

For a more efficient load, you can specify the content within your div:

$('#myDiv').load('current-page.html #onlyNeededSection'); // Be picky about what you fetch

Persisting event binding

Since you're dealing with love towards dynamic content, use delegated events:

$(document).on('click', '#myButton', function() { $('#myDiv').load('endpoint.php #content'); });

This ensures associated events remain intact, even after they've reloaded.