Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Getting API

I'm creating a website where a user clicks "New Quote" and gets a random quote. Here's my site at the moment http://codepen.io/avatar_hzh/pen/OyPobZ. I'm trying to get the quotes from the API here: http://forismatic.com/en/api/ but I'm having trouble using AJAX to use this API. I've watched the AJAX basics videos and still can't seem to get it working. also how do I call the getQuote method described on the forismatic page?

1 Answer

// variable to hold the json response
var data; 

// if you want to see what the response looks like, you can just enter this url into your browser
var url = "api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=callback";

var callback = function( response ) { 
  data = response; 
};

// build a new XML HTTP Request  
var xhr = new XMLHttpRequest();  

// add a method that checks that response has been received and it was successful 
xhr.onreadystatechange = function() {
  if ( xhr.readyState === 4 && xhr.status === 200 ) callback( xhr.response );
};

// predpare the xhr request to be sent 
xhr.open( 'GET', url );

// send request
xhr.send();

The url loaded fine when entered it in my browser but comes back with an 404 error when the AJAX request is sent. So I tried changing the url to http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=callback (added http:// in front of the url and also set the lang parameter to equal "en" so the quote would come back in English) and this time the console comes back with the error:

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=callback. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

I'm guessing this is because by including the http:// in the front I'm now breaking same origin policy. Is there any reason why I can access the response on my browser but not in the AJAX request? Is it because I'm using Codepen and so the GET method doesn't work when the end of the url is appended with the response? Also if the response was working would I need to return the data variable in the callback function to append the response on the web page?