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 trialJess Hines
5,411 PointsWhy doesn't $.ajax() work on this challenge?
Just to explore, I tried to do this challenge using the more-flexible $.ajax()
method, but I get a CORS-related error:
XMLHttpRequest cannot load http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&tags=Dog&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://port-80-ff9i6ym5pp.treehouse-app.com' is therefore not allowed access.
But if I use $.getJSON()
it works as in the video
//this throws the error
$.ajax({
url: flickrUrl,
data: flickrOptions,
success: flickrSuccess
});
//this returns the data as per the video
$.getJSON(flickrUrl, flickrOptions, flickrSuccess);
1 Answer
LaVaughn Haynes
12,397 PointsMy guess is that you probably just need to specify jsonp in your ajax settings object sing you are requesting data from a different server than the one your script is on
dataType: "jsonp"
like this
$(document).ready(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$('form').submit(function (evt) {
var $submitButton = $('#submit');
var $searchField = $('#search');
evt.preventDefault();
$searchField.prop("disabled",true);
$submitButton.attr("disabled", true).val("searching....");
var animal = $searchField.val();
$('#photos').html('');
function flickrSuccess(data){
var photoHTML = '';
if (data.items.length > 0) {
$.each(data.items,function(i,photo) {
photoHTML += '<li class="grid-25 tablet-grid-50">';
photoHTML += '<a href="' + photo.link + '" class="image">';
photoHTML += '<img src="' + photo.media.m + '"></a></li>';
}); // end each
} else {
photoHTML = "<p>No photos found that match: " + animal + ".</p>"
}
$('#photos').html(photoHTML);
$searchField.prop("disabled", false);
$submitButton.attr("disabled", false).val("Search");
}
flickrOptions = {
tags: animal,
format: "json"
};
$.ajax({
url: flickerAPI,
data: flickrOptions,
dataType: "jsonp",
success: flickrSuccess
});
// end ajax
}); // end click
}); // end ready
Jess Hines
5,411 PointsJess Hines
5,411 PointsThat was it! I didn't think I needed that because of the
jsoncallback=?
part of the query, but I did need to adddataType: 'jsonp'
. Thanks!