-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlshortener-jQuerygetpost.js
63 lines (51 loc) · 1.33 KB
/
urlshortener-jQuerygetpost.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
// 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();
$.get(
urlToExpand,
response => {
$responseField.append('<p>Your expanded url is: </p><p>' +
response.longUrl + '</p>');
},
'json'
);
}
function shortenUrl() {
const urlWithKey = url + '?key=' + apiKey;
const urlToShorten = $inputField.val();
$.post({
url: urlWithKey,
data: JSON.stringify({longUrl: urlToShorten}),
dataType: 'json',
contentType: 'application/json',
success(response) {
$responseField.append('<p>Your shortened url is: </p><p>' + response.id + '</p>');
},
error(jqXHR, status, errorThrown) {
console.log(jqXHR);
}
});
}
function expand() {
$responseField.empty();
expandUrl();
return false;
}
function shorten() {
$responseField.empty();
shortenUrl();
return false;
}
// Call functions on submit
$expandButton.click(expand);
$shortenButton.click(shorten);