-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
66 lines (50 loc) · 1.6 KB
/
Copy pathmain.js
File metadata and controls
66 lines (50 loc) · 1.6 KB
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 = 'AIzaSyAxAmxXBn1lS7ZsdXc0fhUP3m3tfTW0ysA';
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 + '?shortUrl=' + $inputField.val() + '&key=' + apiKey;
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
$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){
$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;
}
$expandButton.click(expand);
$shortenButton.click(shorten);