Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same Origin Policy - AJAX & using Public APIs

Tags:

I know if on my own webpage, if my user is on : http://www.example.com/form.php

and I make an ajax request from that page to : http://example.com/responder.php

It will fail because of the Same origin policy (subdomain is different).

What I am trying to understand is, how is it that AJAX requests can pull data from API's like flickr when the request and server are obviously different.


Edit :

eg: Why does this code work?

$.getJSON('http://api.flickr.com/services/rest/?&;method=flickr...' 

(Referred this Community Wiki) Is it using Cross Origin Resource Sharing?

Thanks!

like image 204
DMin Avatar asked Aug 21 '10 07:08

DMin


People also ask

How do you bypass CORS in Ajax?

Rather, you would have to make the external request from your own local php script. Then you would call your local php script from Ajax, and this will work since you are accessing a local file, and thus not violating CORS.

How do you resolve cross origin issues in Ajax?

Re: CORS issue after ajax post requestYour server needs to not only allow POSTs from the origin using Access-Control-Allow-Origin (origin = your Marketo LP domain including protocol, like https://pages.example.com), it also needs to allow the Content-Type header using Access-Control-Allow-Headers.

How do you fix the same origin policy disallows reading the remote resource?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=by+far. This can be fixed by moving the resource to the same domain or enabling CORS.


1 Answers

There are few known methods to work around the Same Origin Policy. One popular technique is to use "Script Tag Injection" such as in JSONP. Since the <script> tag is not constrained by the Same Origin Policy, a script on a third-party domain can provide executable code that interacts with a provided callback function. You may want to check out the "Tips and Tricks" section in the following article for further reading on the topic:

  • Howto Dynamically Insert Javascript And CSS (hunlock.com)

You may also be interested in checking out the following Stack Overflow post for further reading on other techniques to work around the Same Origin Policy:

  • Ways to circumvent the same-origin policy

UPDATE: Further the updated question:

Quoting from the jQuery documentation on $.getJSON():

If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead.

like image 120
Daniel Vassallo Avatar answered Dec 04 '22 18:12

Daniel Vassallo