I have a situation in one of my controllers that should only be accessed via AJAX, I have the following code.
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
When I am testing this gives me an issue because the request hasn’t actually been made via AJAX. This then breaks my tests every time. How should I go about working around this?
My Ideas:
- I have tried to set a server header but have had absolutely no success.
- Check if I am in the test environment in the controller and don’t do the check if it is. I know this is dirty, but it would work. :-/ The problem was that I couldn’t figure out how to discover what environment I am in.
Anyone else have any other ideas or tips that I am missing to get one of the above to work?
Looking at the code for
isXmlHttpRequestin classRequestand methodgetHeadersin classServerBag, the piece of code below should do the trick:I did not test it personally but I think it should works. The line of code below in
Requestis used to check if the http request is aXmlHttpRequest.In the code,
$this->headersis set using:The method
getHeaderscreates an array of headers. Each server variable starting withHTTP_, plus some special server variables likeCONTENT_TYPE, are put in this array.Hope this helps.
Regards,
Matt