-
-
Save codecademydev/cd6351b597d25f345e9108b1e49830cb to your computer and use it in GitHub Desktop.
Codecademy export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Manipulates responseField to render a formatted and appropriate message | |
const renderResponse = (res) => { | |
// Displays either message depending on results | |
if(res.errors){ | |
responseField.innerHTML = "<p>Sorry, couldn't format your URL.</p><p>Try again.</p>"; | |
} else { | |
responseField.innerHTML = `<p>Your shortened url is: </p><p> ${res.shortUrl} </p>`; | |
} | |
} | |
// Manipulates responseField to render an unformatted response | |
const renderRawResponse = (res) => { | |
// Displays either message depending on results | |
if(res.errors){ | |
responseField.innerHTML = "<p>Sorry, couldn't format your URL.</p><p>Try again.</p>"; | |
} else { | |
// Adds line breaks for JSON | |
let structuredRes = JSON.stringify(res).replace(/,/g, ", \n"); | |
structuredRes = `<pre>${structuredRes}</pre>`; | |
responseField.innerHTML = `${structuredRes}`; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Information to reach API | |
const apiKey = '<Your API Key>'; | |
const url = 'https://api.rebrandly.com/v1/links'; | |
const apiKey ='3dea4d8219fd444283eb85f1f85bafb5'; | |
// Some page elements | |
const inputField = document.querySelector('#input'); | |
const shortenButton = document.querySelector('#shorten'); | |
const responseField = document.querySelector('#responseField'); | |
// AJAX functions | |
const shortenUrl = () => { | |
const urlToShorten = inputField.value; | |
const data = JSON.stringify({destination: urlToShorten}); | |
const xhr = new XMLHttpRequest(); | |
xhr.responseType ='json'; | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState === XMLHttpRequest.DONE) { | |
renderResponse(xhr.response); | |
} | |
} | |
xhr.open('POST',url); | |
xhr.setRequestHeader('Content-type', 'application/json'); | |
xhr.setRequestHeader('apikey', apiKey); | |
xhr.send(data); | |
} | |
// Clear page and call AJAX functions | |
const displayShortUrl = (event) => { | |
event.preventDefault(); | |
while(responseField.firstChild){ | |
responseField.removeChild(responseField.firstChild); | |
} | |
shortenUrl(); | |
} | |
shortenButton.addEventListener('click', displayShortUrl); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment