Skip to content

Instantly share code, notes, and snippets.

@jsmayo
Created February 7, 2018 23:54
Show Gist options
  • Select an option

  • Save jsmayo/af47b13ce651c14802b773dd3e7f6c5d to your computer and use it in GitHub Desktop.

Select an option

Save jsmayo/af47b13ce651c14802b773dd3e7f6c5d to your computer and use it in GitHub Desktop.
AJAX Random Dog Pictures S7.L76
<div class="container">
<h1>Welcome To Random Dog Pictures</h1>
<img id="photo" src="https:\/\/dog.ceo\/api\/img\/deerhound-scottish\/n02092002_6780.jpg" alt="">
<button id="btn">Get Random Dog!</button>
</div>
var btn = document.querySelector("#btn");
var img = document.querySelector("#photo");
// listen for clicks
btn.addEventListener("click", function() {
// alert("Clicked");
var XHR = new XMLHttpRequest();
//see when it's ready/done
XHR.onreadystatechange = function() {
if(XHR.readyState == 4 && XHR.status == 200) {
/* console.log(XHR.responseText);
RESONSE: "{'status':'success','message':'https:\/\/dog.ceo\/api\/img\/terrier-norwich\/n02094258_773.jpg'}" */
var url = JSON.parse(XHR.responseText).message;
img.src = url;
}
}
XHR.open("GET", "https://dog.ceo/api/breeds/image/random");
XHR.send();
});
img {
height: 200px;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
}
button {
margin: 20px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment