0

I want to add a product to the cart on the click of a banner. I referred to the fourth answer on this link - Magento 1.9.0.1 add a product to the cart by URL?

But on following the steps as stated, I am getting this error - The requested URL /checkout/cart/add was not found on this server. Can't understand what's wrong.

Would also like to know if there is any alternative approach to this problem

1 Answer 1

0

I just tested this and it works perfectly. All you need are these couple of lines.

<?php $url = $this->helper('checkout/cart')->getAddUrl($_product); ?>
<script>
    setLocation('<?php echo $url; ?>');
</script>

Here is a very basic, yet fully functional example.

  1. Navigave to CMS > Pages in the admin panel and click on your homepage so that the edit screen opens up.
  2. Click on the 'Design' tab, and in the fieldset up top named 'Layout Update XML', add this snippet to it and click save:

    <reference name="before_body_end">
        <block type="core/template" name="custom_banner_js" template="custom/banner/js.phtml"/>
    </reference>
    
  3. Then create this file: app/design/frontend/rwd/astraboot‌/template/custom/banner/js.phtml

  4. In your newly created file, here is the full content to paste into it:

    <?php $_product = Mage::getModel('catalog/product')->load(39); ?>
    <?php $url = $this->helper('checkout/cart')->getAddUrl($_product); ?>
    <script>
        var myImage = $('subscription_product');
        myImage.observe('click',function(){
            setLocation('<?php echo $url; ?>');
        });
    </script>
    
  5. Save your file

  6. Clear your cache

  7. Refresh the page

  8. Test!

Keep in mind, that if you did not remove the <a> tag that was wrapped around the image, this wont work, so just be certain that you removed it.

22
  • I should also mention that you will want to add an event listener for clicks on your banner before invoking setLocation($url) but if you want to test this example, will work like a charm. Aug 17, 2016 at 16:41
  • Thanks Shawn Abramson for your efforts, but since I'm a beginner, can you please tell me which files do I need to edit for the above codes. Aug 17, 2016 at 16:54
  • This code can go into many of the different phtml files. How are you adding the banner to your site? With a CMS static block or in one of the template files? Aug 17, 2016 at 16:57
  • And also, which pages on your site contain the banner? Aug 17, 2016 at 16:58
  • I am using a CMS static block which was already present in the theme I had installed Aug 17, 2016 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.