Skip to content

Instantly share code, notes, and snippets.

@vickonrails
Created October 31, 2017 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vickonrails/34647195b112e6c0731f2bf7c0f7f2b6 to your computer and use it in GitHub Desktop.
Save vickonrails/34647195b112e6c0731f2bf7c0f7f2b6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Async request</title>
</head>
<body>
<p> click on the button to add an image to the page</p>
<button type="button">Get image</button>
<img src="" width="100%">
</body>
<script>
//ES5 for simplicity.
function sendRequest(){
var url;
url = "https://api.unsplash.com/search/photos/?query=home";
var request = new XMLHttpRequest();
request.onreadystatechange = handleRequest;// callback to insert the image into the page...
request.open('GET',url,true);
request.setRequestHeader('Authorization','Client-ID your-unique-id');
request.send();
function handleRequest(){
if(this.readyState === 4 && this.status === 200){
var response = JSON.parse(request.responseText);
var img = document.querySelector('img');
img.src = response.results[0].urls.full;
}
}
}
var btn = document.querySelector('button');
btn.addEventListener('click',sendRequest);//callback to handle the click event...
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment