Check if request was sent by Ajax or not

Magento uses the class Zend_Controller_Request_Http for its requests.

You can use

if ($this->getRequest()->isXmlHttpRequest()) {
    // is Ajax request
}

to detect Ajax requests this way.

At least

  • Prototype
  • Scriptaculous
  • jQuery
  • YUI
  • MochiKit

send the HTTP_X_REQUESTED_WITH header, according to the ZF docs.

Note though, "Ajax requests" means requests sent using XmlHttpRequest (and not using techniques like hidden <iframe>s, or Flash uploaders, or the like) to me.

Since this is subjective and your perception may differ: Magento itself seems to define "Ajax" in some more extended way than I do. Have a look at Mage_Core_Controller_Request_Http::isAjax():

public function isAjax()
{
    if ($this->isXmlHttpRequest()) {
        return true;
    }
    if ($this->getParam('ajax') || $this->getParam('isAjax')) {
        return true;
    }
    return false;
}

Depending on your personal perception of "Ajax", this may (or may not) better fit your needs.


If Im not mistaken, magento is written using Zend Framework, therefor by using the Request object you can do

if($this->getRequest()->isXmlHttpRequest()){
    // ajax
} else {
    // not ajax
}

http://framework.zend.com/manual/en/zend.controller.request.html#zend.controller.request.http.ajax

Good luck! :)

Tags:

Ajax

Magento