I am trying to use an observer to change the response to an add to cart controller action, but only in the context of an AJAX request.
My observer is called , and my JS retrieves the data in order, I checked this by putting die()an observer in my function cartAdd()and checking the answer developer console, which I use to see the result of my answer from Magento. Therefore, JS is not a problem here.
My main problem is that I cannot change the answer through normal functions. I get a request using $observer->getEvent()->getControllerAction()->getResponse(), and then make changes to it setHeader()or setBody()or any other function that modifies the response, but the response effect has absolutely no effect!
Does anyone know why I cannot change the answer in my observer?
In / app / code / local / mynamespace / mymodule / etc / config.xml:
<frontend>
....
<events>
<controller_action_predispatch_checkout_cart_add>
<observers>
<mymodule_cart_add>
<type>singleton</type>
<class>mymodule/observer</class>
<method>cartAdd</method>
</mymodule_cart_add>
</observers>
</controller_action_predispatch_checkout_cart_add>
</events>
</frontend>
In / app / code / local / mynamespace / mymodule / Model / Observer.php:
public function cartAdd(Varien_Event_Observer $observer)
{
$controllerAction = $observer->getEvent()->getControllerAction();
if($controllerAction->getRequest()->isAjax()) {
$response = $controllerAction->getResponse();
$response->setHeader('HTTP/1.1','403 Forbidden');
$response->setHeader('Content-type', 'application/json');
$response->setBody('hello world!!!!');
$controllerAction->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
}
}
Please note: I know that this code is not going to add AJAXify to the cart at all (this is my final goal). At the moment, I'm just trying to solve this problem.
In the end, I just get the contents of the page that you will get as a result of the add to cart action:
