Magento: Custom Javascript Alert After Product Add to Cart

magentomagento-1.7

I've been following various tutorials to try and use Magento event observers to display a custom Javascript alert after a customer adds a product to their cart, but can't seem to get anything. Am I even close to going down the right track?

My Module:

<?xml version="1.0"?>
<config>
    <modules>
        <Shoplio_XS>
            <active>true</active>
            <codePool>local</codePool>
        </Shoplio_XS>
    </modules>
</config>

My config.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <Shoplio_XS>
            <version>0.1.0</version>
        </Shoplio_XS>
    </modules>
    <frontend>
        <events>
            <sales_quote_product_add_after>
                <observers>
                    <Shoplio_XS_Model_Observer>
                        <type>singleton</type>
                        <class>Shoplio_XS_Model_Observer</class>
                        <method>Mytestmethod</method>
                    </Shoplio_XS_Model_Observer>
                </observers>
            </sales_quote_product_add_after>
        </events>
    </frontend>
</config>

My observer.php:

<?php class Shoplio_XS_Model_Observer
{
    public function Mytestmethod($observer) {
        $event = $observer->getEvent();

        // Javascript Alert Here

    } 
}

I'm primarily following this tutorial: http://goo.gl/DRwd5

The only difference is, I don't want to display anything on the shopping cart page because I keep customers on the product page after a product is added to cart. I simply want to display a custom Javascript alert on the product page after the product is added to cart.

Best Answer

You can NOT do Javascript with a Magento Observer because observer code is 'executed' on the server-side, before sending the result back to your browser (while JS is done on the client-side within your browser)

What you can do is

in app/design/frontend/default/[theme]/template/catalog/product/view.phtml

 var productAddToCartForm = new VarienForm('product_addtocart_form');
 productAddToCartForm.submit = function(button, url) {
        if (this.validator.validate()) {

            alert('here');

            var form = this.form;
            var oldUrl = form.action;

            if (url) {
               form.action = url;
            }
            var e = null;
            try {
                this.form.submit();
            } catch (e) {
            }
            this.form.action = oldUrl;
            if (e) {
                throw e;
            }

            if (button && button != 'undefined') {
                button.disabled = true;
            }

        }

 }.bind(productAddToCartForm);
Related Topic