How to Display Success/Error Message on AJAX Request in Magento

ajaxcontrollersevent-observermessagessession

Currently, I am using ajax to add an coupon to the cart. This requires a success/error message to display to the user. However, it seems that i'm unable to retrieve this error/success message without a redirect (something ajax does away with) and the message itself is always displayed on the next pageview.

Is there an easy way to work around this?

The message is set using this in the observer:

Mage::getSingleton('core/session')->setCouponCodeError($error);

This doesn't seem to work in the controller (after the event has been dispatched):

$message = Mage::getSingleton('core/session')->getCouponCodeError();

Best Answer

For ajax calls you need to return the error messages if any. It does not work with $session->addError(). The message you set with addError are picked up on the next page load.

You need to do something like this in your controller:

public function doSomeAjaxStuff()
{
    $response = array();
    $response['success'] = true;
    //do stuff here
    $response['something'] = 'Something';
    if (some error occurs) {
        $response['success'] = false;
        $response['message'] = 'Your error message here';
    }
    $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response); 
}

And in your javascript code that handles the response from the ajax call do this:

if (!response.success) {
    alert(response.message);
    //or insert response.message somewhere in the dom
}