Skip to content

Instantly share code, notes, and snippets.

@abrarShariar
Created May 14, 2017 20:18
Show Gist options
  • Save abrarShariar/22bed3618510422e0ed16f66c6d197e1 to your computer and use it in GitHub Desktop.
Save abrarShariar/22bed3618510422e0ed16f66c6d197e1 to your computer and use it in GitHub Desktop.
Asynchronous search with fetch
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Search with JS</title>
</head>
<body>
<div>
<label>Search For A User On Github: </label>
<input type="text" onkeyup="getText(event)">
<br>
<hr>
<h3>Search Result: </h3>
<div id="result_box">
</div>
</div>
<script>
var result_box = document.getElementById('result_box');
function getText(event) {
var text = event.target.value;
//any remote api endpoint will do
var api = 'https://api.github.com/users/' + text;
fetch(api).then(function (res) {
return res.json();
}).then(function (data) {
console.log(data);
result_box.innerHTML = '';
if (typeof(data) === 'object') {
dataHTML = '<h4>' + 'Name: ' + data['name'] + '</h4>';
dataHTML += '<h5>' + 'Bio: ' + data['bio'] + '</h5>';
dataHTML += '<h5>' + 'Company: ' + data['company'] + '</h5>';
dataHTML += '<img' + 'src="' + data['avatar_url'] + '"/>'
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment