Loading data into HTML Tables using AJAX – JavaScript Tutorial




In most medium-to-large sized websites or applications, it’s ideal to separate your data from your HTML markup. One way to achieve this is by creating a structure in HTML and then loading the data separately from a dedicated data-file.

AJAX is a method of loading data into a web page once it has finished loading – using JavaScript.

In this video I take you through an example of where we populate a HTML table with rows and cell data that comes from an external JSON file. We go through the steps of making the HTTP request, parsing the content and then manipulating the DOM to finally render the data to the user.

For your reference, check this out:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Support me on Patreon:
https://www.patreon.com/dcode

Follow me on Twitter @dcode!

If this video helped you out and you’d like to see more, make sure to leave a like and subscribe to dcode!

Original source


27 responses to “Loading data into HTML Tables using AJAX – JavaScript Tutorial”

  1. I follow along but fail at 8:34 with the following error message:

    Could not load rankings!

    request.onload @ index.html:61

    load (async)

    loadRankings @ index.html:56

    (anonymous) @ index.html:71

    what is this problem about and how to solve it?

    Here is the code:

    <script type="text/javascript">

    const rankingsBody = document.querySelector("#ranking-table > tbody");

    function loadRankings () {

    const request = new XMLHttpRequest();

    request.open("get","data/rankings.json");

    request.onload = () => {

    try {

    const json = JSON.parse(request.responseText);

    populateRankings(json);

    } catch (e) {

    console.warn("Could not load rankings!");

    }

    };

    request.send();

    }

    function populateRankings (json) {

    console.log(json);

    }

    document.addEventListener("DOMContentLoaded", () => {loadRankings(); });

    </script>

  2. Hi very good tutorial I been wanting to do something like that before but I could't, I can do it now but if I add more data to each array it won't run, like more than 3 columns. Does the array have to be the same? Can they contain empty cells or null values?

  3. How can I populate a a table with a JSON output like this?

    [

    {

    "rank": 1,

    "team": "Steeltab",

    "country": "Kyrgyzstan",

    "player": {

    "one": "Laurie",

    "two": "Rowland"

    },

    "points": 2019

    }
    ]

    Extremely good and clear tutorial btw!

  4. It looks cool! But, I have a little problem: Getting the data from a PHP file using the json_encode method, the resulting JSON it's very different from the one you created, because is made of arrays and the json are made of objects. Could you make a video teaching how to do it in that case? I will appreciate it a lot
    Thanks for this video

Leave a Reply