How to get json data from a url using vanilla javascript only ?

Active March 20, 2022    /    Viewed 1361    /    Comments 0    /    Edit


Examples of how to get json data from a url using only vanilla javascript:

Video: tips For Using Async/Await in JavaScript

I was looking for to remove JQuery and replace it by only vanilla javascript to increase the speed of my websites (in particular by replacing all ajax calls that retrieve json data from n url). Found a lot of documentations online (see references below) but the following youtube video by James Q. Quick summarized everything very well:


Get json data from url using Fetch API

A first solution is to use the Fetch API. An example here with
json data stored on github:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

        <script>

            const url = 'https://raw.githubusercontent.com/benjamin-hg-marchant/datasets/main/modis_cloud_phase_time_series_analysis.json'

            fetch(url)
                .then( res => { return res.json(); } )
                .then( data => { console.log(data); } )
                .catch( err => { console.errror(error) } )

        </script>

    </body>
</html>

Get json data from url using an asynchronous function

Another approach is to use await (Note that await must always be used inside an asynchronous function)

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

        <script>

                const LoadData = async () => {
                    try {
                        const url = 'https://raw.githubusercontent.com/benjamin-hg-marchant/datasets/main/modis_cloud_phase_time_series_analysis.json'

                        const res = await fetch(url);
                        const data = await res.json();
                        console.log(data);
                    }catch(err) {
                        console.error(err)
                    }
                };

                LoadData();

        </script>

    </body>
</html>

Note that the LoadData function returns a promise and can be then used inside another async function:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

        <script>

                const LoadData = async () => {
                    try {
                        const url = 'https://raw.githubusercontent.com/benjamin-hg-marchant/datasets/main/modis_cloud_phase_time_series_analysis.json'

                        const res = await fetch(url);
                        const data = await res.json();
                        console.log(data);
                    }catch(err) {
                        console.error(err)
                    }
                };

( async () => {
 const data = await LoadData();
 console.log(data);
} )();

        </script>

    </body>
</html>

Another approach using then:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

        <script>

                const LoadData = async () => {
                    try {
                        const url = 'https://raw.githubusercontent.com/benjamin-hg-marchant/datasets/main/modis_cloud_phase_time_series_analysis.json'

                        const res = await fetch(url);
                        const data = await res.json();
                        console.log(data);
                    }catch(err) {
                        console.error(err)
                    }
                };

                LoadData().then( (data) => console.log(data) );

        </script>

    </body>
</html>

Create a non cached request

Note that the header can be specified in the fetch API to create a non cached request on the client side for example (see fetch(), how do you make a non-cached request?, Fetch PUT request gets Cache-Control header modified on Firefox and not Chrome and Fetch caching response - no-cache headers not working as expected):

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

        <script>

                const LoadData = async () => {
                    try {
                        const url = 'https://raw.githubusercontent.com/benjamin-hg-marchant/datasets/main/modis_cloud_phase_time_series_analysis.json'

                        const res = await fetch(url,{
                        method: 'GET', // *GET, POST, PUT, DELETE, etc.
                        mode: 'cors', // no-cors, *cors, same-origin
                        cache: 'no-cache'});
                        const data = await res.json();
                        //console.log(data);
                        return data;
                    }catch(err) {
                        console.error(err)
                    }
                };

                LoadData().then( (data) => console.log(data) );

        </script>

    </body>
</html>

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount