.xhr? returns nil on remote requests

Something that confused the hell out of me, was when I wanted to so some AJAX request, I wanted to use methode .xhr? in the controller, to see, whether it was an ajax or regular request.

Turns out a request by a form or a link with remote: true, does not contain the header X-Requested-With that this method checks for.

So why include a handy method to the request object, if it is not usable with a standard ajax request.

for reference from ActionDispatch::Request

# Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
# (case-insensitive), which may need to be manually added depending on the
# choice of JavaScript libraries and frameworks.
def xml_http_request?
  get_header("HTTP_X_REQUESTED_WITH") =~ /XMLHttpRequest/i
alias :xhr? :xml_http_request?

I’m guessing that you had to work around this issue by defining some other method that peeked at some other aspect of the request.

Is that the case? If so, what was that workaround?

I actually did not find a workaround in time, my google foo failed me. I decided to just not care, as I don’t care too much about supporting usage without JS anyway.

Stackoverflow only pretty much shows one answer, which is outdated, no discussion around it.

I find it surprising that .xhr? returns 0 or nil.

1 Like

It won’t be the case anymore: Revert "Merge pull request #37504 from utilum/no_implicit_conversion_… · rails/rails@e67fdc5 · GitHub