Xhr and format.js

I am getting confused about the relationship between
respond_to/format.js and an xhr request. Would appreciate any advice,
tips on how this has changed in different Rails versions if it has, etc.

In particular, I am confused as to why an xhr request sometimes will
trigger format.js, even though it’s not actually a request to
format=>js, but other times won’t. And if I want to take some special
action in response to xhr requests, is it best practice to check
request.xhr?, or to use format.js?

I am adding some unobtrusive JQuery JS of my own (not using the Rails
helpers), which submit to the same controller actions as the ordinary
HTML actions. But when a request is received from an xhr, the controller
should do something different – for instance, not do a redirect, or
return just a partial instead of the full HTML (the JQuery will grab the
partial and insert it into the page itself).

What is the best practice for having a controller action recognize an
xhr request, and respond differently? In some sample code on the net, I
see “format.js”. Which confuses me a bit, because the JS code isn’t
actually making a .js request, it’s still requesting .html – but
sometimes format.js seems to match it anyway, and I don’t know why.
Other times it does not. I can not predict it.

Or, I can actually manually test for “if request.xhr” and just “render”
what I want manually if so, if not do the whole respond_to thing. But
that gets a bit odd too.

Are there best practices for this stuff? For having a controller action
that responds differently to an xhr request from JS than to an ordinary
browser HTML request? When I google around, people seem all over the
place on this, it seems to have changed a lot in different rails
versions, etc.

Any advice appreciated.