Skip to content

Instantly share code, notes, and snippets.

@javedbaloch4
Created October 31, 2020 12:04
Show Gist options
  • Save javedbaloch4/51eba036a1d3469200be0c561018eee0 to your computer and use it in GitHub Desktop.
Save javedbaloch4/51eba036a1d3469200be0c561018eee0 to your computer and use it in GitHub Desktop.
JS Fetch API Examples.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<title>Works</title>
</head>
<body>
<div class="container mt-5">
<button class="btn btn-warning" id="getText">Get Text</button>
<button class="btn btn-primary" id="getUsers">Get Users</button>
<button class="btn btn-success" id="getPosts">Get Users</button>
<p id="output"></p>
<form action="" id="addPost">
<div>
<input type="text" id="title" placeholder="Title">
</div>
<div>
<textarea id="body" placeholder="Body"></textarea>
</div>
<button type="submit">Submit</button>
</form>
</div>
<script>
document.getElementById("getText").addEventListener("click", getText);
document.getElementById("getUsers").addEventListener("click", getUsers);
document.getElementById("getPosts").addEventListener("click", getPosts);
document.getElementById("addPost").addEventListener("click", addPost);
function getText() {
fetch("sample.txt")
.then((res) => res.text())
.then((data) => {
document.getElementById("output").innerHTML = data
})
.catch((error) => console.log(error))
}
function getUsers() {
fetch('users.json')
.then((res) => res.json())
.then((data) => {
let output = "<h1>Users</h1>";
data.forEach(function(user) {
output += `
<ul>
<li>ID: ${user.id}</li>
<li>Name: ${user.name}</li>
<li>Email: ${user.email}</li>
</ul>
`;
});
document.getElementById("output").innerHTML = output;
})
}
function getPosts() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => {
let output = "<h3>Posts</h3>";
data.forEach(function(post) {
output += `
<div>
<h3>${post.title}</h3>
<p>${post.body}</p>
</div>
`
})
document.getElementById("output").innerHTML = output
})
}
function addPost(e) {
e.preventDefault();
let title = document.getElementById("title").value;
let body = document.getElementById("body").value;
// For Post API
fetch("https://jsonplaceholder.typicode.com/posts", {
method: 'POST',
headers: {
'Accept' : 'application/json, text/plain, */*',
'Content-type' : 'application/json'
},
body: JSON.stringify({title: title, body: body})
})
.then((res) => res.json())
.then((data) => console.log(data))
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment