Request III || XHR GET request not working


#1

Here is my code.

// Include data for accessing Google APIs

const apiKey = '<AIzaSyCypLir66EOpI80W4Xhz3GHOIku3ydAh9U>';
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);
      console.log($responseField.append('<p>Your expanded url is: </p><p>' + xhr.response.longUrl + '</p>'));
			}
  }
  xhr.open('GET', urlToExpand);
  xhr.send();
}

function shortenUrl() {

}

function expand() {
  $responseField.empty();
  expandUrl();
  return false;
}

function shorten() {
  $responseField.empty();
  shortenUrl();
  return false;
}

// Call functions on submit

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

when i run it, i constantly seeing messeages ‘Your expanded url is: undefined’

And in the console,

VM5072:1 GET https://www.googleapis.com/urlshortener/v1/url?key=<AIzaSyCypLir66EOpI80W4Xhz3GHOIku3ydAh9U>&shortUrl=https://goo.gl/cjyLB1 400 ()
(anonymous) @ VM5072:1
expandUrl @ main.js:25
expand @ main.js:34
dispatch @ jquery-3.1.0.min.js:3
q.handle @ jquery-3.1.0.min.js:3
main.js:20 {error: {…}}
main.js:21 r.fn.init [div#responseField]

this error.

what should i do?


#2

I could be wrong but I think the issue MIGHT be that you need to remove < > from your const apiKey code. So it looks like this: const apiKey = ‘AIzaSyCypLir66EOpI80W4Xhz3GHOIku3ydAh9U’;

Forgive me if this doesn’t help you at all. Still learning myself.


#3

Thanks! Your reply means a lot :slight_smile:

Have a nice day! (thogh it’s already bed time here haha)