The Zend Framework provides a neat function in its request object called isXmlHttpRequest(). The following is therefore possible:
public function someAction()
{
if ($this->getRequest()->isXmlHttpRequest()) {
// AJAX request specific parts
}
}
Zend_Controller_Request_Http::isXmlHttpRequest() checks internally if the request header X-Requested-With is set to “XMLHttpRequest”. If this condition is fullfilled, the request is considered an XH request. However, Prototype, jQuery and YUI set this request in their XHR abstractions, Dojo does not. The following snippet helps to set this in Dojo:
dojo.xhrGet({
url: <url>,
load: <callback>,
headers: {"X-Requested-With": "XMLHttpRequest"}
});
This stucks the X-Requested-With header into the XMLHttp-request and isXmlHttpRequest() will return bool(true).
What the others do
Interesting to see that Rails is a bit more generous in what it accepts as an XHR. As this header is a pseudo standard it would be worth doing it exactly the same way as Rails does it. Nothing is worse than a pseudo standard with slightly different implementations.
def xml_http_request?
!(@env['HTTP_X_REQUESTED_WITH'] !~ /XMLHttpRequest/i)
end
The RequestHandlerComponent from CakePHP provides a method isAjax() in the stricter Zend Framework variant. Django, Pylons and TurboGears seem not to provide such helpers.
Comments
Show comments linear or threaded
Josh replies:
published on 2008|02|09, 00:03hYour blog is double encoding html entities and making it near impossible to follow anything like code or urls.
Josh supposes:
published on 2008|02|09, 00:05hEdit: It seems it only happens when I view from an rss feed and serendipity auto-highlights things as search terms.
My bad.
Peritus opines:
published on 2008|02|09, 09:29hIn django it looks somewhat like this:
http://www.djangosnippets.org/snippets/572/
Lars Strojny replies:
published on 2008|02|09, 10:16hA fine, thanks for it.
Add comment