Thursday 10 November 2016

Simple way to Add Product To Cart Using Ajax in Magento

In this blog post, i am going to tell how to add products to shopping cart using ajax and jquery.Shopping cart is an essential part of any E-commerce website.
In magento the add to cart process is a simple form submit process, so the page get reloaded.Therefore, Ajax based Shopping Cart comes as a solution to fasten the buying process.

Ok lets start step by step.
1. First add jQuery on the Product Page.
2. Then Create folder jquery in root js folder.
3. Download jQuery from http://jquery.com/download/ and then place it inside (/js/jquery) folder.
4. Create a javascript file “noconflict.js” in the jquery folder (/js/jquery/noconflict.js).
5. Write this code inside noconflict.js file
jQuery.noConflict();
6. Open catalog.xml file in your theme folder [app/design/frontend/base/default/layout/catalog.xml in default magento theme]
7. Inside tag <catalog_product_view> write this code
<reference name=”head”>
<action method=”addItem”><type>js</type><name>jquery/jquery-1.6.4.min.js</name></action>
<action method=”addItem”><type>js</type><name>jquery/noconflict.js</name></action>
</reference>
8. Open any product page in frontend in a browser, through inspector, see if these two jquery files are included in your page.
9. Open the catalog/product/view.phtml file in your theme (rwd,base or any custom theme) in default magento theme,
the path is (app\design\frontend\base\default\template\catalog\product\view.phtml)
In this file you will find the javascript code as
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
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);
10. Change this code to
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
// Start of our new ajax code
if (!url) {
url = jQuery(‘#product_addtocart_form’).attr(‘action’);
}
url = url.replace(“checkout/cart”,”ajax/index”); // New Code
var data = jQuery(‘#product_addtocart_form’).serialize();
data += ‘&isAjax=1’;
jQuery(‘#ajax_loader’).show();
try {
jQuery.ajax({
url: url,
dataType: ‘json’,
type : ‘post’,
data: data,
success: function(data){
jQuery(‘#ajax_loader’).hide();
//alert(data.status + “: ” + data.message);
if(jQuery(‘.block-cart’)){
jQuery(‘.block-cart’).replaceWith(data.sidebar);
}
if(jQuery(‘.header .links’)){
jQuery(‘.header .links’).replaceWith(data.toplink);
}}
});
} catch (e) {
}
// End of our new ajax code
this.form.action = oldUrl;
if (e) {
throw e;
}
}
}.bind(productAddToCartForm);
11. Go to phtml file catalog/product/view/addtocart.phtml
and then find this code there
<button type=”button” title=”<?php echo $buttonTitle ?>” class=”button btn-cart” onclick=”productAddToCartForm.submit(this)”><span><span><?php echo $buttonTitle ?>
</span></span></button>
12. Change this to
<button type=”button” title=”<?php echo $buttonTitle ?>” class=”button btn-cart” onclick=”productAddToCartForm.submit(this)”><span><span><?php echo $buttonTitle ?></span></span></button>
<span id=’ajax_loader’ style=’display:none’><img src='<?php echo $this->getSkinUrl(‘images/opc-ajax-loader.gif’)?>’/></span>
13. Open your product page again and when you press the add to cart button, you should see a loading image and ajax request being sent.
14. Create a custom module with namespace Sneh_Ajax.(Register it in app/etc/modules and create its config.xml in app/code/local/Sneh/Ajax/etc folder).
15. In directory (app/code/local/Sneh/Ajax/controllers),create a file IndexController.php and add a function AddAction
<?php
require_once ‘Mage/Checkout/controllers/CartController.php’;
class Sneh_Ajax_IndexController extends Mage_Checkout_CartController
{
public function addAction()
{
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
if($params[‘isAjax’] == 1){
$response = array();
try {
if (isset($params[‘qty’])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array(‘locale’ => Mage::app()->getLocale()->getLocaleCode())
);
$params[‘qty’] = $filter->filter($params[‘qty’]);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam(‘related_product’);
/**
* Check product availability
*/
if (!$product) {
$response[‘status’] = ‘ERROR’;
$response[‘message’] = $this->__(‘Unable to find Product ID’);
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(‘,’, $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* @todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent(‘checkout_cart_add_product_complete’,
array(‘product’ => $product, ‘request’ => $this->getRequest(), ‘response’ => $this->getResponse())
);
if (!$cart->getQuote()->getHasError()){
$message = $this->__(‘%s was added to your shopping cart.’, Mage::helper(‘core’)->htmlEscape($product->getName()));
$response[‘status’] = ‘SUCCESS’;
$response[‘message’] = $message;
//New Code Here
$this->loadLayout();
$toplink = $this->getLayout()->getBlock(‘top.links’)->toHtml();
$sidebar_block = $this->getLayout()->getBlock(‘cart_sidebar’);
Mage::register(‘referrer_url’, $this->_getRefererUrl());
$sidebar = $sidebar_block->toHtml();
$response[‘toplink’] = $toplink;
$response[‘sidebar’] = $sidebar;
}}
catch (Mage_Core_Exception $e) {
$msg = “”;
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode(“\n”, $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message.'<br/>’;
}}
$response[‘status’] = ‘ERROR’;
$response[‘message’] = $msg;}
catch (Exception $e) {
$response[‘status’] = ‘ERROR’;
$response[‘message’] = $this->__(‘Cannot add the item to shopping cart.’);
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper(‘core’)->jsonEncode($response));
return;}
else{
return parent::addAction();
}}}
16. Save the file and go back to the product page.
17. Now add to cart using ajax should be working properly.
18. After clicking add to cart, you can see an alert box with success message.


Visit our Blog for daily updates or you can visit our website abacasys.com to check our services 

No comments:

Post a Comment