What is the difference between


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
XHR Post Requests III

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
No error; just question. Why does shortenURL function need to ‘POST’ while expandURL need to ‘GET’??

```

Replace this line with your code.
// Include data for accessing Google APIs

const apiKey = ‘AIzaSyA3NW3TCS6y8hAuciPrst7-Q8ZyeVsXX2k’;
const url = ‘https://www.googleapis.com/urlshortener/v1/url’;
const projection = ‘FULL’;

// 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) {
$responseField.append('

Your expanded url is:

’ + xhr.response.longUrl + ‘

’);
}
}

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('

Your shortened url is:

’ + xhr.response.id + ‘

’);
}
}

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);

<do not remove the three backticks above>

#2

https://www.w3schools.com/tags/ref_httpmethods.asp


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.