Request I || XHR Post Request II


#1

Tasks are correct but my response is not shown. What’s wrong?


#2

Please post your raw code and a link to the exercise. Thanks.


#3

exercise: https://www.codecademy.com/courses/intermediate-javascript-requests/lessons/requests-i/exercises/xhr-post-requests-iii?action=lesson_resume&course_redirect=introduction-to-javascript

// Include data for accessing Google APIs

const apiKey = 'Your API key';
const projection = 'FULL';

// Some page elements

const $inputField = $('#input');
const $expandButton = $('#expand');
const $shortenButton = $('#shorten');
const $responseField = $('#responseField');

// AJAX functions

function expandUrl() {

}

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

// Call functions on submit

$expandButton.click(expand);
$shortenButton.click(shorten);


#4

url is not defined. Is that line meant to follow the line after it?

const urlToShorten = $inputField.val();
const urlWithKey = urlToShorten + '?key=' + apiKey;

#5

Honestly I don’t know, just learning requests…


#6

I’ve done that unit twice but CC keeps eating my code, otherwise I might have an answer for you. Did your try my suggestion?


#7

I tried, doesn’t work.


#8

Okay, skip the earlier suggestion. Add this line to the top, just under your key…

const url = 'https://www.googleapis.com/urlshortener/v1/url';

Now url is defined.


#9

Yeeees! I just found it out, I had to delete this line accidentally. thanks!


#10

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