Created
April 24, 2018 15:18
-
-
Save chongiscool/cee521e61f54defd8c007a0f6df1866a to your computer and use it in GitHub Desktop.
JS 'GET' & 'POST' request all process from codecademy.
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
// Include data for accessing Google APIs | |
const apiKey = 'api_key'; | |
const projection = 'FULL'; | |
const url = 'https://www.googleapis.com/urlshortener/v1/url'; | |
// Some page elements | |
const $inputField = $('#input'); | |
const $expandButton = $('#expand'); | |
const $shortenButton = $('#shorten'); | |
const $responseField = $('#responseField'); | |
// AJAX functions | |
// most expand operation in here | |
function expandUrl() { | |
const urlToExpand = url + '?key=' + apiKey + | |
'&shortUrl=' + $inputField.val(); | |
const xhr = new XMLHttpRequest(); | |
xhr.responseType = 'json'; | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === XMLHttpRequest.DONE) { | |
console.log(xhr.response); | |
$responseField.append('<p>Your shortend url is: </p><p>' + xhr.response.id + '</p>'); | |
$responseField.append('<p>Your expanded url is: </p><p>' + xhr.response.longUrl + '</p>'); | |
} | |
} | |
xhr.open('GET', urlToExpand); | |
xhr.send(); | |
} | |
// most shorten operation in here | |
function shortenUrl() { | |
const urlWithKey = url + '?key=' + apiKey; | |
const urlToShorten = $inputField.val(); | |
const data = JSON.stringify({ | |
longUrl: urlToShorten | |
}); | |
const xhr = new XMLHttpRequest(); | |
xhr.responseType = 'json'; | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState === XMLHttpRequest.DONE) { | |
console.log(xhr.response); | |
$responseField.append('<p>Your shortened url is: </p><p>' + xhr.response.id + '</p>'); | |
} | |
} | |
xhr.open('POST', urlWithKey); | |
xhr.setRequestHeader('Content-Type', 'application/json'); | |
xhr.send(data); | |
} | |
function expand() { | |
$responseField.empty(); | |
expandUrl(); | |
return false; | |
} | |
function shorten() { | |
$responseField.empty(); | |
shortenUrl(); | |
return false; | |
} | |
// Call functions on submit | |
$expandButton.click(expand); | |
$shortenButton.click(shorten); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment