ToroPHP icon indicating copy to clipboard operation
ToroPHP copied to clipboard

Better method of checking if request is XHR

Open pastudan opened this issue 11 years ago • 6 comments

While most AJAX frameworks have support for the X-Requested-With header, others are dropping it, citing low usage.

Angular: https://github.com/angular/angular.js/commit/3a75b1124d062f64093a90b26630938558909e8d

I also believe this is a better way of determining what content to send back for building APIs, despite that it is not actually checking whether the request was XHR.

pastudan avatar Nov 08 '13 21:11 pastudan

I think this will cause a regular curl request with a json header to appear as ajax?

jasonmoo avatar Nov 08 '13 21:11 jasonmoo

only if application/json is the first mime type that it accepts. It is checking if the position of that string is 0, and the default curl header is Accept: */*, so we should be fine.

pastudan avatar Nov 08 '13 21:11 pastudan

What makes this method better? You’re just checking if the accepted Content-Type is application/json. Although JSON is a popular choice for AJAX requests, they’re not mutually exclusive.

martinbean avatar Nov 08 '13 21:11 martinbean

I may be completely wrong in my approach, but since angular doesn't send the X-Requested-With header, it makes more sense to me to check what sort of data the user is requesting: either text/html vs application/json, application/xml, etc, and return the appropriate response.

If someone were developing an Android / iPhone app, would you recommend setting the X-Requested-With, or Accept header in order to get data rather than HTML?

Again, this may be the wrong place to change this.. please correct my if I have made some wrong assumptions.

pastudan avatar Nov 08 '13 22:11 pastudan

If frameworks like Angular are no longer sending an X-Requested-With HTTP header, then it makes sense to accompany that.

I’m not sure about just checking the Content-Type as if say, a web browser sends it then it’s going to get erroneously treated as an AJAX request in Toro terms.

I’m not against the approach, but think it needs some further discussion.

martinbean avatar Nov 08 '13 22:11 martinbean

Agreed.. was just hoping to get that conversation started. After your comment, I realize my solution only covers JSON, and there are definitely other cases we need to catch.

Just to clarify, Content-Type is the header on the server's response. Accept is the header on the client request and the one my code looks at... In theory, a web browser will always send Accept: text/html, application/xhtml+xml, application/xml, ... and the order is what typically determines a response. If the server can't provide html or xhtml, it should drop down to application/xml, etc. I believe all browsers do this currently.

pastudan avatar Nov 08 '13 22:11 pastudan