jQuery.ajax fails when url is from different server

Why does jQuery.ajax() throw an error with no error message if you use a URL with a dfferent server?


Its because of the restriction on cross domain requests implemented in the browser for XMLHttpRequests. You can get around this by using JSONP as the format, otherwise you'll need a server-side proxy for the request.

Quoting from the ajax documentation on http://jquery.com

Note: All remote (not on the same domain) requests should be specified as GET when 'script' or 'jsonp' is the dataType (because it loads script using a DOM script tag). Ajax options that require an XMLHttpRequest object are not available for these requests. The complete and success functions are called on completion, but do not receive an XHR object; the beforeSend and dataFilter functions are not called.


As http://en.wikipedia.org/wiki/Cross-origin_resource_sharing says:

Cross-origin resource sharing (CORS) is a mechanism that allows a web page to make XMLHttpRequests to another domain.1 Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request.2 It is more powerful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests.

For PHP it is done using header() function:

<?php
header("Access-Control-Allow-Origin: http://example.com");
?>

CORS can be used as a modern alternative to the JSONP pattern. While JSONP supports only the GET request method, CORS also supports other types of HTTP requests. Using CORS enables a web programmer to use regular XMLHttpRequest, which supports better error handling than JSONP. On the other hand, JSONP works on legacy browsers which preclude CORS support. CORS is supported by most modern web browsers. Also, whilst JSONP can cause XSS issues where the external site is compromised, CORS allows websites to manually parse responses to ensure security.

JSONP or "JSON with padding" is a communication technique used in JavaScript. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.


The ajax() method internally uses XmlHttpRequest which obeys the same domain policy http://en.wikipedia.org/wiki/Same_origin_policy. The getJson() method can be used instead for making cross domain calls.

I hope this helps, Bogdan