Magento 1.7 – Execute Custom JavaScript on sales_order_place_after Event

event-observerlayoutmagento-1.7

I need to execute some custom JavaScript right after the sales_order_place_after event is fired for collecting analytic data.

I know how to make an observer and do something in the relevant method. But how do I load and execute a custom JavaScript on the frontend/admin depending on how the order was placed?

Right now, I have created the module, added the config.xml, and have created an observer with following code.

<?php
class Namespace_module_Model_observer
{
    public function doSomeThing($observer)
    {
        $order = $observer->getEvent()->getOrder();

        //do something here to load the custom javascript and execute it
        //whether the order was placed from backend or frontend
    }
}

The observer method is getting executed when the order is placed. What should be the correct approach to achieve my custom functionality?

Note: I have to keep in mind that my observer code doesn't interfere with the checkout steps as the customer might/might not be redirected to payment gateway for further processing depending on the payment method chosen.

Best Answer

So in no way I'm saying this is best practice but you could get the layout in the observer and add a Javascript tag to the head block for example.

Still, there must be a better way to do whatever you wanna do. Maybe update your question with whatever you want to accomplish

$layout = Mage::app()->getLayout();
$layout->getUpdate()->addUpdate('
reference name="head">
    <block type="core/text" name="myjs">
        <action method="setText"><text><![CDATA[<script type="text/javascript">
// put your JS here
</script>]]></text></action>
    </block>
</reference>');
$layout->getUpdate()->load();
$layout->generateXml();
Related Topic