• Skip to main content
  • Skip to primary sidebar

WordPress, Genesis Framework and Storefront customization tutorials

  • Archive
    • Free
    • Premium
  • Blog
  • About
  • Contact
  • Newsletter
  • Membership
  • Login
Home » fetch

fetch

Fetch API – Local text, json, external API – with Arrow Functions

Get Local Text File Data

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

Get Local JSON Data

function getJson() {
  fetch('posts.json')
    .then(res => res.json())
    .then(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(err => console.log(err));
}

Get External API Data

function getExternal() {
  fetch('https://api.github.com/users')
    .then(res => res.json())
    .then(data =>  {
      console.log(data);
      let output = '';

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

    })
    .catch(err => console.log(err));
}

Filed Under: Free Tagged With: fetch

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: Free Tagged With: fetch

Fetch API with Bootstrap 5

View Demo

HTML

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.83.1">
    <title>Breaking Bad API with Bootstrap 5</title>
    <link rel="icon" href="#">

    <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/album/">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">


    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>

    
  </head>
  <body>
    
<header>
  <div class="collapse bg-dark" id="navbarHeader">
    <div class="container">
      <div class="row">
        <div class="col-sm-8 col-md-7 py-4">
          <h4 class="text-white">About</h4>
          <p class="text-muted">Add some information about the album below, the author, or any other background context. Make it a few sentences long so folks can pick up some informative tidbits. Then, link them off to some social networking sites or contact information.</p>
        </div>
        <div class="col-sm-4 offset-md-1 py-4">
          <h4 class="text-white">Contact</h4>
          <ul class="list-unstyled">
            <li><a href="#" class="text-white">Follow on Twitter</a></li>
            <li><a href="#" class="text-white">Like on Facebook</a></li>
            <li><a href="#" class="text-white">Email me</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <div class="navbar navbar-dark bg-dark shadow-sm">
    <div class="container">
      <a href="#" class="navbar-brand d-flex align-items-center">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="me-2" viewBox="0 0 24 24"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
        <strong>Fetch API</strong>
      </a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarHeader" aria-controls="navbarHeader" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
    </div>
  </div>
</header>

<main class="bg-dark">

  <section class="py-5 text-center container">
    <div class="row py-lg-5">
      <div class="col-lg-6 col-md-8 mx-auto">
        <h1 class="fw-light text-white">Breaking Bad API</h1>
        <p class="lead text-muted">Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don’t simply skip over it entirely.</p>
        <p>
          <a href="#" id="button1" class="btn btn-lg btn-primary my-2 bg-danger bg-gradient border-0">Get Data</a>
        </p>
      </div>
    </div>
  </section>

  <div class="album py-5 bg-dark">
    <div class="container">

      <div id="output" class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">

      </div>
    </div>
  </div>

</main>

<footer class="text-muted py-5 bg-dark">
  <div class="container">
    <p class="float-end mb-1">
      <a href="#">Back to top</a>
    </p>
    <p class="mb-1">Album example is &copy; Bootstrap, but please download and customize it for yourself!</p>
    <p class="mb-0">New to Bootstrap? <a href="/">Visit the homepage</a> or read our <a href="/docs/5.0/getting-started/introduction/">getting started guide</a>.</p>
  </div>
</footer>


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

      
  </body>
</html>

JavaScript

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

// Get external API data
function getExternal() {
  fetch('https://www.breakingbadapi.com/api/characters ')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      // This is an array so we have to loop through it
      let output = '';

      data.forEach(function(character){
        output += `
        <div class="col">
        <div class="card text-center border-0">
          <div class="card-img-top" style="
            background-image: url(${character.img});
            background-size: cover;
            width: 100%;
            height: 500px;
          "></div>
          <h4 class="card-header">
            ${character.name} (${character.nickname})
          </h4>
          <ul class="list-group list-group-flush">
            <li class="list-group-item">${character.portrayed}</li>
            <li class="list-group-item">${character.occupation}</li>
          </ul>
        </div>

          <div class="card shadow-sm">
          </div>
        </div>
        
        `;
      });
      document.getElementById('output').innerHTML = output; 

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

Filed Under: Free Tagged With: fetch

Primary Sidebar

Gabor Flamich

Hi! I'm Gabor.
I write tutorials on WordPress and WooCommerce.

MacBook

12 Essential Snippets for Genesis Developers

Subscribe to my Newsletter to view my basic collection of Genesis snippets that I use for my projects!

Sign Up for Free
  • Facebook
  • GitHub
  • Instagram
  • LinkedIn
  • Twitter
  • YouTube
UpdraftPlus Premium

Tags

ACF Ajax Analytics API Bootstrap Breadcrumb category CPT CSS fetch Genesis Google Maps Gutenberg HTML Isotope JavaScript jQuery loop Map Menu Parallax PHP SASS SEO SQL Storefront SVG tab tag manager tags Taxonomy Tool upsell Webpack Wholesale WooCommerce WordPress WPML

Disclosure: Some of the links in this site are affiliate links. I will be paid a commission if you use this link to make a purchase.

  • Privacy Policy / Terms of Service
© 2023 WP Flames - All Right Reserved