jQuery and cross domain AJAX requests

Updated . Posted . Visible to the public.

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
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2014-07-17 08:22)