JavaScript Lessons

AJAX Dynamic Content Loading: Fetch API Examples

Load HTML and data in the background with AJAX and the Fetch API. Update parts of your page without a full reload and keep the experience smooth.

Serhat ALPASLAN2 min read

Loading dynamic content with AJAX lets you update a web page’s content by fetching it in the background, without the page having to reload. This means users see content changes instantly, and the page loads faster too.

To do this, you can request data from the server with AJAX and then update that data on your page. For example, when a link on a web page is clicked, you can fetch data from the server in the background and update just a specific part of the page.

As an example, the code snippet below fetches the file “data.txt” in the background when a link is clicked and writes it into the “content” div:

 

<a href="#" id="link">Click me</a>
<div id="content"></div>

<script>
  var link = document.getElementById("link");
  link.addEventListener("click", function(e) {
    e.preventDefault(); // prevent the link's default behavior
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "data.txt", true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        document.getElementById("content").innerHTML = xhr.responseText;
      }
    };
    xhr.send();
  });
</script>

In this example, when the “link” element is clicked, it fetches the file “data.txt” in the background and writes the incoming data into the “content” div. This happens without the page having to reload, and the user sees the content change instantly.

Loading dynamic content with AJAX doesn’t just speed up page loading by fetching data in the background — it also lets you change how the page looks. For instance, when a user runs a search on a website, data can be fetched from the server in the background and the results updated on the page.

This way, the user sees the search results instantly, with no need to reload the page. What’s more, with AJAX dynamic content loading you can make many different content changes on a page. For example, on an e-commerce site, different sections such as the product list, cart contents or invoice details can be loaded in the background.

Finally, loading dynamic content with AJAX doesn’t just improve the performance of web applications — it also improves the user experience. Using this technology will make web pages faster and more interactive.

Share it if it helped

Write a comment