Read more

jQuery and cross domain AJAX requests

Tobias Kraze
July 17, 2014Software engineer at makandra GmbH

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.
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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
Posted by Tobias Kraze to makandra dev (2014-07-17 10:22)