Skip to content

Instantly share code, notes, and snippets.

@gma
Created December 14, 2012 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gma/4285182 to your computer and use it in GitHub Desktop.
Save gma/4285182 to your computer and use it in GitHub Desktop.
Setting the HTML_X_REQUESTED_WITH header in jQuery, which doesn't seem to be set for me unless I force it. If I don't set this, Rails concludes that I'm not making an xhr request and tries to serve HTML, even though the HTTP_ACCEPT header is clearly set to `application/json, text/javascript, */*`.
$.ajax @api_url,
dataType: 'json'
beforeSend: (jqXHR, settings) ->
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
success: (data, textStatus, jqXHR) =>
@onDataLoaded(data, textStatus, jqXHR)
callback?()
error: (jqXHR, textStatus, errorThrown) =>
@onLoadFailed(jqXHR, textStatus, errorThrown)
@gma
Copy link
Author

gma commented Dec 14, 2012

Another note; what's weird is that jQuery doesn't set this header naturally. Note that if you try and set it by calling setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") (as it's often documented online) it doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment