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
Jose Linares
5,062 PointsJSON working, JSONP not. Please help
I did the Ajax course and I learned that in order to access an API from another server I had to use JSONP. Well this API has three links, one in XML, another in JSON and the last one in JSONP, and when I try to use the JSONP link nothing happens no error, message, no data, nothing; but when I use the JSON links it works perfect. Why is this? Dave McFarland said that because of the same-origin security policy we could not use JSON from another server. I'm really confused. Here is the links to the API documentation: https://yts.to/api
Please help me. Thanks
Jose Linares
5,062 PointsRight now I'm just trying to access the data and log it:
var API = "https://yts.to/api/v2/list_movies.jsonp";
function success(data) {
console.log(data);
}
$.getJSON(API, success);
2 Answers
Kenneth Black
23,140 PointsLooks like because of the quirks of JSONP, it needs a callback in the query string. Just add "?callback=?" to the end of the url string. The following code worked for me.
var API = "https://yts.to/api/v2/list_movies.jsonp?callback=?";
function success(data) {
console.log(data);
}
$.getJSON(API, success);
Kenneth Black
23,140 Pointsnot 100% sure on <em>why</em> it works, mind you. JSONP feels a little like a workaround in general.
Jose Linares
5,062 PointsWell it worked for me too. So thank you so much for taking the time. I don't know why it works either but, what else can i do. Thanks
Kenneth Black
23,140 PointsKenneth Black
23,140 PointsIf you could post your code, that would be helpful. Worth noting is that it is possible to do AJAX requests across origin now, it just needs to be enabled on their end. From what I understand, JSONP uses a different method of data transmission, basically emulating a script tag to send data, so it has some different rules, of which I'm currently looking into.