Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a button call a function that uses the fetch API

I'm practicing using the fetch API for a project I'm working on and having trouble getting a button to call a function that uses the fetch API to access an external API. Keep getting a 'Type Error: Failed to Fetch' message.

const uri = 'https://jsonplaceholder.typicode.com/posts';
    const initDetails = {
        method: 'get',
        headers: {
            "Content-Type": "application/json; charset=utf-8"
        },
        mode: "cors"
    }
    
    function getData() {
        fetch(uri, initDetails)
        .then(response => {
            if (response.status !== 200) {
                console.log('Looks like there was a problem. Status Code: ' +
                response.status);
                return;
            }
    
            console.log(response.headers.get("Content-Type"));
            return response.json();
            }
        )
        .then(myJson => {
            console.log(JSON.stringify(myJson));
        })
        .catch(err => {
            console.log('Fetch Error :-S', err);
        });
    }
    
    window.onload=function() {
        let myButton = document.getElementById("getData");
        myButton.addEventListener('click', getData);
    }
<form>
    <button id='getData'>Get Data</button>
   </form>
like image 384
Jayce Avatar asked Nov 01 '25 05:11

Jayce


1 Answers

Your button is inside a form. The default action of buttons inside forms is to submit the form, which reloads the page and aborts the fetch request.

Either preventDefault() in the form submit handler, add type="button" to the <button> element, or (ideally, in this case) remove the <form> entirely.

like image 127
AuxTaco Avatar answered Nov 02 '25 19:11

AuxTaco