Skip to content

Instantly share code, notes, and snippets.

@jnf
Last active June 27, 2017 03:18
Show Gist options
  • Save jnf/5f228f1e4ec6e859f5d7ca57f2d1f85a to your computer and use it in GitHub Desktop.
Save jnf/5f228f1e4ec6e859f5d7ca57f2d1f85a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quotes OMG!</title>
</head>
<body>
<div id="quote"></div>
<form id="apiOptions" onsubmit="handleSubmit()">
<fieldset>
<legend>Format</legend>
<label>
<input type="radio" name="format" value="text" checked>Text
</label>
<label>
<input type="radio" name="format" value="html">HTML
</label>
<label>
<input type="radio" name="format" value="json">JSON
</label>
</fieldset>
<input type="submit" name="submit" value="Quote Me!">
</form>
<!-- <button type="button" onclick="getQuote()">Quote Me!</button> -->
<script type="text/javascript" src="quotes.js"></script>
</body>
</html>
const apiURL = "https://uwpce-fortune-proxy.herokuapp.com/"
const form = document.getElementById("apiOptions")
// const apiURL = "https://uwpce-fortune-proxy.herokuapp.com/?format=html"
let debug = null
function handleSubmit () {
event.preventDefault()
console.log(form)
// get form values
let values = {format: form.format.value}
// serialize them into a query string
let queryString = queryBuilder(values)
// call getQuote with the query string
getQuote(queryString)
}
function getQuote (queryString) {
let request = new XMLHttpRequest()
// starts talk to API - 3 params
// request method, url, (optional) async flag (default true)
request.open("GET", apiURL + queryString, true)
// fires when the request is complete
// long term - I want to update the DOM
request.onload = function () {
let quoteDiv = document.getElementById("quote")
let response = JSON.parse(request.response)
console.log(response.body)
// debug = response
quoteDiv.innerHTML = response.body
}
// fires if something goes wrong
request.error = function (errorObject) {
console.log("bwoken :(")
console.log(errorObject)
}
// send the request!
request.send()
}
function queryBuilder(queryObj){
let holder = []
// loop through queryObj key value pairs
for(let key in queryObj){
// turn each one into "key=value"
let convert = `${encodeURIComponent(key)}=${encodeURIComponent(queryObj[key])}`
// encodeURIComponent converts spaces and & to URI friendly values so we don't have to worry about them
holder.push(convert)
}
// concatenate the pairs together, with & between
let longString = holder.join("&")
// prepend a ? to concatenated string, return
return `?${longString}`
}
// document.addEventListener("DOMContentLoaded", function () {
// let btnQuote = document.querySelector("button")
// btnQuote.addEventListener("click", getQuote)
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment