DEV Community

Discussion on: Vanilla JS to Jquery: The Noobs Guide

Collapse
 
scott_yeatts profile image
Scott Yeatts • Edited

The web is a crazy place and has a lot of old tutorials out there. All of this will work (because of backwards compatibility), BUT there is a better way (that a developer just learning JavaScript might never know how to find, because there are a TON of jQuery examples that use the old XMLHttpRequest AJAX calls.)

If you look towards the bottom of the Wikipedia link in your story, you'll see a header for the "Fetch Alternative". For practical daily programming, it's the "Fetch Replacement" as it's been implemented in every modern browser.

If you have to support IE (Please don't... supporting IE has gotten to the point that it is literally unethical to write code for it. You can tell companies this until you're blue in the face, but some just refuse to stop installing a virus onto their machines hahaha), there is a polyfill.

Fetch API Docs
Fetch Polyfill

So that would change your vanilla JS implementation to:

<body>
    <button id="myFirstCall">Javascript: Get Data</button>
</body>
<script>
    async function getResponse() {
        try {
            const response = await fetch('https://demo3269086.mockable.io/abc123');
            const myJson = await response.json();
            console.log(myJson);
        } catch(err) {
            console.log(err)
        }
    };
    document.getElementById('myFirstCall').onclick = function() {
        getResponse();
    }
</script>

OR, if you love the .then syntax from promises:

<body>
    <button id="myFirstCall">Javascript: Get Data</button>
</body>
<script>
    function getResponse() {
        const response = fetch('https://demo3269086.mockable.io/abc123');
        response.then(res => {
            res.json().then(jsonRes => {console.log(jsonRes)});
        })
        .catch(err => {
            console.log(err);
        }) 
    };
    document.getElementById('myFirstCall').onclick = function() {
        getResponse();
    }
</script>

fetch just lends itself to a slightly more condensed, but MUCH more readable code, that improves on the XMLhttpRequest syntax, and is both thenable, so it can use the Promise API that followed XMLHttpRequest, or the newer async/await format.

It also removes ANY external dependency (which is the real benefit... no need to include jQuery)

Both of those examples were tested in a bare HTML file from my desktop with no

other code in the file. Copy and paste them exactly into an HTML file on your desktop and (except for the mock implementation) they should "just work™"

Collapse
 
th3n00bc0d3r profile image
Muhammad

Great Response .. Cheers Up... would you like to co-author a book I am compiling. Its just wonderful to find helping hands over here. Your context could be used to further make a stronger concept of how things work on a basic level, so that a strong grip on higher level code is achievable.