• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / JavaScript / Fetch API – Local text, json, external API

Fetch API – Local text, json, external API

View Demo

Fetch API is a new standard for dealing with http requests.

Get Local Text File Data

document.getElementById('button1').addEventListener('click', getText);

function getText() {
  fetch('test.txt')
    .then(function(res){
      return res.text();
    })
    .then(function(data) {
      console.log(data);
      document.getElementById('output').innerHTML = data;
    })
    .catch(function(err){
      console.log(err);
    });
}

Get Local JSON Data

document.getElementById('button2').addEventListener('click', getJson);

// Get local json data
function getJson() {
  fetch('posts.json')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      console.log(data);
      // This is an array so we have to loop through it
      let output = '';

      data.forEach(function(post){
        output += `<li>${post.title}</li>`;
      });
      document.getElementById('output').innerHTML = output;

    })
    .catch(function(err){
      console.log(err);
    });
}

Get external API data

document.getElementById('button3').addEventListener('click', getExternal);

function getExternal() {
  fetch('https://api.github.com/users')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      console.log(data);
      // This is an array so we have to loop through it
      let output = '';

      data.forEach(function(user){
        output += `<li>${user.login}</li>`;
      });
      document.getElementById('output').innerHTML = output;

    })
    .catch(function(err){
      console.log(err);
    });
}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" />
  <link rel="icon" href="#">
  <title>Ajax Sandbox</title>
</head>
<body>
  <div class="container">
    <h1>Fetch API Sandbox</h1>
    <button id="button1">Get Text</button> 
    <button id="button2">Get JSON</button>
    <button id="button3">Get API Data</button>
    <br><br>
    <div id="output"></div>
  </div>

  <script src="app.js"></script>
</body>
</html>

Filed Under: JavaScript Tagged With: fetch

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved