jQuery and cross domain AJAX requests

When making cross-domain AJAX requests with jQuery (using CORS Show archive.org snapshot or xdomain or similar), you will run into issues with HTTP headers:

  • jQuery will not set the X-Requested-With header. On your server, requests will not look like AJAX requests (request.xhr? will be false).
  • jquery-ujs Show archive.org snapshot will not set CSRF headers.

This is by design and improves security.

In order to send those headers for specific hosts, add this piece of CoffeeScript directly after jQuery (but before jquery-ujs):

whitelisted = (url) ->
  for domain in ["http://trusted.host/", "https://another.trusted.host/"]
    return true if url.indexOf(domain) == 0
  false

$.ajaxPrefilter (options) ->
  if whitelisted(options.url)
    options.crossDomain = false
Tobias Kraze Almost 10 years ago