December 30, 2024
1 min read

Fetch data from API is very simple in js. let’s begin the coding of js fetch post API data.

We will use JSONPlaceholder – Free Fake REST API (typicode.com)

1s we need have a markup with HTML like below

Markup for API data
<div role="status" id="loading">
    <div class="spinner-border">
        loading...
    </div>
</div>
<div class="post_area" id="posts"></div>

Now comes the main part of Javascript code to fetch api data. on API URL use your own API. in the loop your API maybe not provide data in the main variable. use console.log(list) to understand the data structure. You may need to use list.data or something else.

JS api fetching code
// api url
const api_url = "https://jsonplaceholder.typicode.com/users/1/posts";

// Defining async function
async function getapi(url) {
// Storing response
const response = await fetch(url);

// Storing data in form of JSON
var data = await response.json();
//   console.log(data);
if (response) {
    hideloader();
}
show(data);
}
// Calling that async function
getapi(api_url);

// Function to hide the loader
function hideloader() {
document.getElementById("loading").style.display = "none";
}
// Function to define innerHTML for HTML table
function show(list) {
let single_post = "";
// Loop to access all item
for (let n of list) {
    single_post += `<div class="single_post">
    <h4>${n.title}</h4>
    <p>${n.body}</p>
    </div>`;
}
// Setting innerHTML to push data inside posts div
document.getElementById("posts").innerHTML = single_post;
}
JS fetch post July 26, 2021

Ok now put css as you like and enjoy 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

Implementing WooCommerce Shop Page Quantity Input and Plus (+) Minus (-) Button with simple Code

Enhance the user experience on your WooCommerce website by adding quantity plus minus buttons and a quantity option on the shop page.

WordPress Next and Previous Post

WordPress Next and Previous Post navigation for custom post type and defult blog post simple php code to use single page

Customizing WooCommerce Order Numbers with Prefix and Year Suffix

Customize WooCommerce order numbers your way, whether you prefer code or a plugin. Add unique prefixes and dynamic year-based suffixes effortlessly. Make your store’s orders truly yours!

JQuery Auto Hight

jQuery height change after a specific time interval

Web Development Project in mind?

if you looking for a web developer for paid contribution to your project I am available for work.

Mukto
Mukto

Click the button below to chat with me.