Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this cross-domain ajax call actually work?

I inadvertently wrote a cross-domain AJAX call to NextBus (with jQuery):

$.ajax({
      url: 'http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=sf-muni&r=1&s=6294',
      dataType: 'xml',
      success: function(data) {
           do_stuff();
      }
});

Thing is, it works on all browsers, despite coming from a different domain. Given the Single Origin Policy, why does this actually work?

The page is here: http://sftransitfirst.org/F/, selecting a stop from the pull-down triggers the ajax.

As expected, making a similar call to the Google Maps API Web Services fails with the familiar Origin ... is not allowed by Access-Control-Allow-Origin (and it doesn't support jsonp).

like image 970
carillonator Avatar asked Aug 28 '12 15:08

carillonator


People also ask

What is Cross domain AJAX?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.

How do I make a cross domain AJAX call?

You can allow Cross Domain Ajax calls to an application by just registering a new filter and then configure it to Allow-Origin : {your domain's} or you can use a wild card “*” to allow the calls from all domains.

Can I send AJAX request to another domain?

Cross-origin resource sharing (or CORS) can be used to make AJAX requests to another domain.

How does an AJAX call work?

How AJAX Calls Work. AJAX uses both a browser built-in XMLHttpRequest object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML.


2 Answers

They must have explicitly allowed cross-domain access, with something of this manner:

<?php header('Access-Control-Allow-Origin: *'); ?>

Or with htaccess:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</ifModule>
like image 116
Alexander Wigmore Avatar answered Oct 14 '22 20:10

Alexander Wigmore


Many modern web APIs enable Cross-Domain Resource Sharing (CORS). CORS is a method for websites to voluntarily make their pages available to cross-domain scripts. The Access-Control-Allow-Origin HTTP header from the server signals to your web browser that it is okay to allow the script to access the page with Ajax, even if the script is running on a different origin. If the server does not serve CORS headers, your browser will enforce the SOP as usual.

Most APIs choose to expose their pages to cross-domain scripts because they know that virtually all of their users will want to be able to access the API via Ajax from their own domains.

like image 5
apsillers Avatar answered Oct 14 '22 20:10

apsillers