Javascript example to Fetch JSON using http GET

In this post, we describes the simple example of javascript code which is used to get the JSON from remote server ( although we have shown as localhost, you can change it to remote server url ) and print it to browser console.

First, lets create the demo json in our server as,

$ vim demo.json 
[
        {
                "name" : "abcdefg",
                "class" : "first"
        },
        {
                "name" : "xyz",
                "class": "fifth"
        }
]

Now, we will write the html code which has the javascript code to fetch this json,

$ vim fetchjson.html 
<html>
        <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

                <h1> Fetch JSON using JavaScript </h1>
        </head>
        <body>
                <script>
                        var weburl = 'http://localhost/test.json';
                        $.ajax({
                                method: 'GET',
                                url: weburl,
                                dataType: "json",
                                success: function(data) {
                                        console.log(data);
                                },
                                error: function(error) {
                                        console.log(error);
                                }
                        })
                </script>
        </body>
</html>

As you can see above, the actual java code which fetch the json is,

 <script>
        var weburl = 'http://localhost/test.json';
        $.ajax({
            method: 'GET',
            url: weburl,
            dataType: "json",
            success: function(data) {
                console.log(data);
            },
            error: function(error) {
                console.log(error);
            }
        })
    </script>

the code is very simple, we have defined “weburl” where we are fetching the JSON. method: “GET” declares it has http GET request. dataType is “json” to declare we are fetching JSON, “success:function(data)” is called after successful download of the JSON from the server. If our json is not present at the url, http GET will return “404 (Not Found)”

Now, lets copy this demo.json and fetchjson.html to our local machines apache webserver /var/www/html and open fetchjson.html in browser as, http://localhost/fetchjson.html

now, when we open the browser console, we can see the JSON as,

This is similar to jquery API https://api.jquery.com/jQuery.getJSON/

Leave a Comment