I'm confused with all the 'json', 'jsonp', 'localhost' and 'CORS' concepts

Hello Everybody!! I manage to finish the Random Quote Machine as you can see in this Codepen [I know the styles are still ugly and the quote just appears after the first click, I’m working on it ATM].

In order to make it work I had to set datatype on ajax as ‘jsonp’ otherwise I won’t be able to retrieve th json file from the API but this is really confusing, so my questions are:

  • is this happening beacause I’m working on my localhost and not on a real Live server?
  • If AJAX request are limited to connections between the same domain, then what’s the right way to do it when you are working on a live server? using json or jsonp?

Thanks in advance for your help!

PS: I know maybe some of this questions or the way I define concepts may sound ridiculous to you… as I say, I’m really lost trying to undertand this so sorry!

PS2: If there some documentation, articles or guides you think I should read to get the grasp of all this subjects, please share with me.

1 Like

Take a look at the following links I posted in another topic :

Here are some additional links I found useful on the topic of “Cross Domain Scripting” :

  1. Ways to circumvent the “Same-Origin Policy” : javascript - Ways to circumvent the same-origin policy - Stack Overflow
  2. Cross-Domain requests in Javascript : Cross-Domain requests in Javascript | jvaneyck
  3. JSON Proxy : https://jsonp.afeld.me/
  4. Using CORS : web.dev
  5. Making Cross-Domain requests with CORS : Making Cross-Domain Requests with CORS
  6. Successful Cross Origin Resource Sharing (CORS) Using A Proxy Server : Successful Cross Origin Resource Sharing (CORS) Using A Server Proxy - Brian Prom Blog
6 Likes

Thanks a lot for your answer… I’ve been reading all pf your links and also other ones I’ve found and I feel I understand a lot better all this concepts, however there’s two doubts I still have:

  • By using the $.ajax() method I’m doing a CORS request by default?
  • I used my CORS Request code on Codepen and still got an error Origin 'http://s.codepen.io' is therefore not allowed access.Does this mean that the API can´t handle CORS requests?

Bonus question:

  • How can I update my code to use CORS request on Chrome?

If they provide a JSONP API then you need to add a callback at the end of the params ?callback=foo I believe.

Or use a Vanilla JS Snippet to handle the JSONP request.