/usr/portage

Dojo and the Zend Framework 4

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.

Filed under , , , , , , & four comments & no trackbacks