-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurlshortener-example.js
66 lines (53 loc) · 1.63 KB
/
urlshortener-example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Include data for accessing Google APIs
const apiKey = 'AIzaSyAzCems3-NaPDxmLWMuoPMNiSRyginEmYs';
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
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 expanded url is: </p><p>' + xhr.response.longUrl + '</p>');
}
};
xhr.open('GET', urlToExpand);
xhr.send();
}
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);