Magento – Ajax Add to Cart from Product Page Using jQuery

In this article, we are going to discuss about How to create an Ajax based Add to Cart from Product Page Using jQuery in Magento. This is just going to be a quick snippet. One thing I get asked a lot is how to add a product to the cart using ajax and its actually quite easy to do. Now I'm not going to go over how to use jQuery with Magento because there are plenty of tutorials on how to do that. I am going to assume you have jQuery setup in Magento.

<script type="text/javascript"> 
  (function($) 
  { 
    $(document).ready(function() 
    { 
      // Setup the click event 
      $('#product_addtocart_form').submit(addToCart); 
       
    }); 
     
    function addToCart(e) 
    { 
      e.preventDefault(); 
       
      // Here You Should Validate Your Information.  
      // For example if you have options that need to be selected like shirt size 
       
      // Now get the forms data 
      var formData = $('#product_addtocart_form').serialize(); 

      // Now because we are adding the cart through ajax you need to add this so the controller knows that it is ajax and can pass back json if there is an error 
      formData += '&isAjax=1'; 
       
      // Send the form data over 
      $.ajax({ 
        url:$('#product_addtocart_form').attr('action'), 
        type:'POST', 
        data:formData, 
        dataType:'json', 
        success:function(data) 
        { 
          // Do what you want. You have added a product to your cart 
          // I Like to show my persistant cart popup here 
        } 
      }); 
    } 
       
  })(jQuery); 

</script>

Create an Ajax Coupon / Discount Code Box in Magento

In this article, we are going to discuss about How to create an Ajax Coupon / Discount code box in Magento. Basically this will set you up with the new extension you are going to create. The only thing in the tutorial that you do not need to do is putting any information in the controller file. I am going to assume you have followed the tutorial and you are ready to edit your CartController.php. To start off your file is going to look like this.

<?php 
require_once 'Mage/Checkout/controllers/CartController.php'; 
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController 


}

This is our basic controller file. With this any functions we write that have the same name as the Mage Cart Controller will now be overwritten. this is great if you ever need to make changes like adding ajax functionality to any other parts of magento. Next we add the following code and our file should look like this.

<?php 
require_once 'Mage/Checkout/controllers/CartController.php'; 

class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController 

function couponPostAction() 

 // if not ajax have parent deal with result 
  
 if(!isset($_POST['ajax'])) 
 { 
parent::couponPostAction(); 
return; 
 } 
  
 $msg = ''; 
  
 $couponCode = (string) $this->getRequest()->getParam('coupon_code'); 
 if ($this->getRequest()->getParam('remove') == 1) { 
 $couponCode = ''; 
 } 
 $oldCouponCode = $this->_getQuote()->getCouponCode(); 

 if (!strlen($couponCode) && !strlen($oldCouponCode)) { 
 $this->_goBack(); 
 return; 
 } 

 try { 
 $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true); 
 $this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '') 
 ->collectTotals() 
 ->save(); 

 if ($couponCode) { 
 if ($couponCode == $this->_getQuote()->getCouponCode()) { 
 $this->_getSession()->addSuccess( 
 $this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode)) 
 ); 
 } 
 else { 
$msg = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode)); 
 } 
 } else { 
 $this->_getSession()->addSuccess($this->__('Coupon code was canceled.')); 
 } 

 } catch (Mage_Core_Exception $e) { 
 $msg = $e->getMessage(); 
 } catch (Exception $e) { 
  $msg = $this->__('Cannot apply the coupon code.'); 
 Mage::logException($e); 
 } 
  
 echo $msg; 

}

So basically what we do is check for a POST variable called ajax. If this does not exist then we know not to use our ajax code so let the regular code run or the parents code if you will. If it is available then we continue. The code is essentially the same as it's parent except instead of putting any errors into a session variable and send the browser back a page, we are echoing out any error messages. If the $msg variable is empty then we know there were no errors.

Now we can move on to our form and javascript. Our form should look something like the following

<div class="box"> 
  <strong class="ttl">DISCOUNT CODE</strong> 
  <p>Enter your coupon code if you  have one</p> 
  <form id="discountcode-form" action="<?= $this->getUrl('checkout/cart/couponPost') ?>" name="discountcode-form" method="post"> 
    <div class="text discount-code"><input type="text" name="coupon_code" value="SUBMIT YOUR CODE" /></div> 
    <input type="submit" class="btn-apply" value="APPLY"/> 
  </form> 
</div>

This is just your basic discount code form. You can make any design modifications as you want the only things that are important are the form tags and the input box. Once you have your form you will want to create the following javascript

$('#discountcode-form').submit(function(e) 

  e.preventDefault(); 
   
  $.ajax({ 
    url:$('#discountcode-form').attr('action'), 
    type:'POST', 
    data:'ajax=true&'+$('#discountcode-form').serialize(), 
    success:function(data) 
    { 
      if(data != '') 
      { 
        // Display error message however you would like 
      } 
    } 
  }); 
});

What this script does is takes the action url from the form and passes all of the forms data to our php script using the jQuery ajax function. It then listens for a response. If it getts something other then null you can take that message and display it however you like.

If you have any questions please let me know and as always leave your feedback...

File Upload and Validation in CodeIgniter

In this article, we are going to discuss about How to do the file upload and validation in CodeIgniter. I would like to explain how to upload files to server in CodeIgniter and to validate it with Form Validation library.

  1. How to upload files to server
  2. How to Validate file before uploading
  3. How to upload files to server

Step 1 :

Create a view that contains form fields and a field with input type file (Register.php) and add the below code in that file.

<?php echo form_open_multipart('welcome/register/'); ?>

form_open_multipart is used to upload files. It supports the input type file. Next we have to add other form fields and fiel field.

<?php echo validation_errors('<p class="form_error">','</p>'); ?>
<?php echo form_open_multipart('welcome/register/'); ?>
<input type="text" name="firstname" placeholder="Enter your Firstname"/>
<input type="text" name="city" placeholder="Enter your City"/>
<input type="file" name="userimage">
<button type="submit">Create Account</button>
</form>

Step 2:

Now, the form is submitted to the Register method in Welcome controller. Our Register method in Welcome contoller looks like this Welcome.php

public function register(){
     $this->load->library('form_validation');
     $this->form_validation->set_rules('firstname', 'First Name', 'required|trim|xss_clean');
     $this->form_validation->set_rules('city', 'City', 'required|trim|xss_clean');
     $this->form_validation->set_rules('userimage', 'Profile Image', 'callback_image_upload');
     if($this->form_validation->run() == TRUE){
         echo "Account Created Successfully";
     }
     $this->load->view('register');
}

Step 3:

Create a callback function for uploading image and validation. Method image_upload looks like the following.

function image_upload(){
      if($_FILES['userimage']['size'] != 0){
        $upload_dir = './images/';
        if (!is_dir($upload_dir)) {
             mkdir($upload_dir);
        }  
        $config['upload_path']   = $upload_dir;
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['file_name']     = 'userimage_'.substr(md5(rand()),0,7);
        $config['overwrite']     = false;
        $config['max_size']  = '5120';
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('userimage')){
            $this->form_validation->set_message('image_upload', $this->upload->display_errors());
            return false;
        }  
        else{
            $this->upload_data['file'] =  $this->upload->data();
            return true;
        }  
    }  
    else{
        $this->form_validation->set_message('image_upload', "No file selected");
        return false;
    }
}

Explaining the callback function.

Steps Involved are

  • First we are checking if the file is submitted with the form. If the file is empty, we are setting the form validation error message as "No file selected".
  • We are creating a directory if the directory does not exist.
  • We have to configure the directory path, allowed upload files, filename, maximum file size, maximum width, maximum height etc.,
  • Then we are uploading the file. If upload fails, error message is set to the form validation.


Hope this is helpful.

Yii – Load modules dynamically from db or directory

In this article, we are going to discuss about How to load the modules dynamically from DB or from Directory in YII framework. In Yii application development, we can set up modules configuration in config.php.  Sometimes, we need to load modules configuration from database or directory glob. After searching the topic in google and comparing some solutions, I found the elegant way to implement this. Hope it can help.

You can modify the index.php file of your Yii application.

require_once($yii);

class ExtendableWebApp extends CWebApplication {
        protected function init() {
                // this example dynamically loads every module which can be found
                // under `modules` directory
                // this can be easily done to load modules
                // based on MySQL db or any other as well
                foreach (glob(dirname(__FILE__).'/protected/modules/*', GLOB_ONLYDIR) as $moduleDirectory) {
                        $this->setModules(array(basename($moduleDirectory)));
                }
                return parent::init();
        }
}

$app=new ExtendableWebApp($config);
$app->run();

Reference: http://www.yiiframework.com/forum/index.php/topic/23467-dynamically-load-modules-models-and-configurations/page__p__144316#entry144316

Magento Functional and Factory class groups

In this article, we are going to discuss about the Functional and Factory class groups in Magento. As you know Magento is built based on module architecture, which leads to the requirement that there must be an interaction between modules. Hence, in this part we will learn about the way these modules used.

Definition and Examples of Functional and Factory class groups

Functional Class
  •     Class: only contains functions and static attributes? (not sure)
  •     For example: Mage

Factory Class

  •     Class: consists of functions to create the instance (object) of different Classes. Class depends on input parameters
  •     For example: class Mage

Create an instance of class Mage_Catalog_Model_Product

Mage::getModel('catalog/product')

Generate an instance of class Mage_Catalog_Block_Product_View

Mage::getBlockSingleton('catalog/product_view')

Definition of Instance, the ways to create the instance object in Magento

  • Definition : In OOP, Instance is an Object
  • Create an instance object in Magento

Mage::getModel('catalog/product');
Mage::getBlockSingleton('catalog/product_view');
Mage::app()->getLayout()-createBlock('catalog/product_view')

The process to generate an instance through the function Mage::getModel() is as below:

1) Call function getModel() trong class Mage

2) Call function getModelInstance() in class Mage_Core_Model_Config

3) Call function getModelClassName(). This function will return the name of the model with catalog/product is Mage_Catalog_Model_Product.

4) Add a new object by the New command:

$obj = new $className($constructArguments);

In this example, $className = 'Mage_Catalog_Model_Product'

Get different instances from different places:

– With creating a Instance of a model, the function Mage::getModel() always returns a new object (instance).

– Function Mage::getSingleton() always gives only one object (instance) back.

Download and install Drupal modules using Drush

In this article, we are going to discuss about How to download and install Drupal modules using Drush command. One of the best things about building websites with Drupal is that there are thousands of modules that help you quickly create functionality.

To set things up, you need to download Drush and add it to your path. For example, you might unpack it into /opt/drush and then add the following line to your ~/.bashrc:

PATH=/opt/drush:$PATH
export PATH

Reload your ~/.bashrc with source ~/.bashrc, and the drush command should become available. If you're on Microsoft Windows, it might need some more finagling. (Or you can just give up and use a virtual image of Linux to develop your Drupal websites.

Drush is a huge time-saver. For example, I install dozens of modules in the course of building a Drupal website. Instead of copying the download link, changing to my sites/all/modules directory, pasting the download URL into my terminal window after wget, unpacking the file, deleting the archive, and then clicking through the various module enablement screens, I can just issue the following commands to download and enable the module.

drush dl modulename
drush en -y modulename
(The -y option means say yes to all the prompts.)

So much faster and easier. You can use these commands with several modules (module1 module2 module3), and you can use drush cli to start a shell that's optimized for Drush.

Drush is also useful if you've screwed up your Drupal installation and you need to disable themes or modules before things can work again. In the past, I'd go into the {system} table and carefully set the status of the offending row to 0. Now, that's just a drush dis modulename.

Drush has a bucketload of other useful commands, and drush help is well worth browsing. Give it a try!

Web Site Tour Builder - Joomla extension download

Web Site Tour Builder module is very easy to use and allow you to create a very cool tour in simple steps. Web Site Tour Builder gives you the ability to create amazing tour which easily arouse visitor interest, with a User Friendly Backend, highly customizable solution to build your tour into your site.

Features

  1. Support Continued Tour in Multiple Pages
  2. 5 Types of Display ad ( Button, Link, Autostart on Load, LightBox on Load, Manual )
  3. 3 Types of Popup Box ( Modal, Tooltip, Nohighlight )
  4. 3 Selectors Type ( id, class, name) You can append tour to all html class
  5. 4 Positions (Top, Bottom, Left, Right )
  6. Draggable Box
  7. Keywords Controls to change step
  8. Rotation Control
  9. Steps Title
  10. Steps Text with Editor WYSIWYG for J3
  11. Redirect to Control

Usefult to continue tour in multiple pages

  • 2 Popup Tour Themes
  • 2 LightBox Themes
  • Cookies Options - to not show always the tour

Compatible With All recents Popular Browsers

  • Google Chrome
  • Firefox
  • Safari
  • Opera
  • Internet Explorer(IE7+)


Check this short tutorial video here: https://www.youtube.com/watch?v=mOdl9xbQAEw

Extension Name: Web Site Tour Builder

Price: Paid (€ 19,00)

More info and reviews: Web Site Tour Builder on JED

For Demo - Click Here

Download Paid Version - Click Here

For Documentation - Click Here

Export data as CSV from database in CodeIgniter

In this article, we are going to discuss about How to export the data as CSV from database in CodeIgniter. In CodeIgniter we can export data easily from database as CSV using a library called dbutil. We can pass the query result directly into the dbutil function and we can download the data as CSV.

In your model, write down a function called exportCSV as mentioned below.

function ExportCSV()
{
$this->load->dbutil();
    $this->load->helper('file');
    $this->load->helper('download');
    $delimiter = ",";
    $newline = "\r\n";
    $filename = "filename_you_wish.csv";
    $query = "SELECT * FROM table_name WHERE 1";
    $result = $this->db->query($query);
    $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
    force_download($filename, $data);
}

You can change the filename and the database query as per your needs. Call this function from your controller.

Populate dropdown values in Cakephp using AJAX

In this article, we are going to discuss about How to populate the dropdown values in Cakephp using AJAX. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP. CakePHP uses well-known software engineering concepts and software design patterns, such as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.

Step 1 :

Add the below code in your View File where you want to apply the Ajax Dropdown

<div id="zoneDiv"></div>

<script>
$(document).ready(function(){
    $('#HotelCountryId').change(function(){
        var countryID = $(this).val();
        $.ajax({
            dataType: "html",
            type: "POST",
            evalScripts: true,
            url: '<?php echo Router::url(array('controller'=>'zones','action'=>'ajaxzone'));?>',
            data: ({countryid:countryID}),
            success: function (data, textStatus){
                $("#zoneDiv").html(data);
          
            }
        });
    });
});
</script>

Step 2 :

Add the below code in your Controller function from where you want to populate data

public function ajaxzone($id = null) {
    // debug($this->request->data['countryid']);exit;
    $this->layout = 'ajax';
    $id = $this->request->data['countryid'];
    if (!$this->Zone->exists($id)) {
        throw new NotFoundException(__('Invalid zone'));
    }
    $options = array('conditions' => array('Zone.country_id' => $id));
    $this->set('zones', $this->Zone->find('list', $options));
}

Step 3:

The view file of this function ajaxzone.ctp

<?php   
  echo $this->Form->input('zone_id', array('class'=>'form-control','placeholder'=>'State'));
?>

Create a XML and JSON web service using WordPress

In this article, we are going to discuss about How to create a XML and JSON web service using Wordpress. WordPress started in 2003 with a single bit of code to enhance the typography of everyday writing and with fewer users than you can count on your fingers and toes. Since then it has grown to be the largest self-hosted blogging tool in the world, used on millions of sites and seen by tens of millions of people every day.

Create a wordpress page and call it json or whatever you like and then add a json.php file within your wordpress theme then add the code below.

<?php
/*
Template Name: json
*/

/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

  /* soak in the passed variable or set our own */
  $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
  $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
  $user_id = intval($_GET['user']); //no default

  /* connect to the db */
  global $wpdb;

  /* create one master array of the records */
  $posts = array();
  
  $the_query = new WP_Query( "author=$user_id&showposts=$number_of_posts" );

  while ( $the_query->have_posts() ) : $the_query->the_post();
         
// add any extras that you would like to this array 
$posts[] = array('title'=> get_the_title(),'content'=>get_the_content(),'link'=>get_permalink(get_the_ID()));

  endwhile;


  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
  }
  else {
    header('Content-type: text/xml');
    echo '<posts>';
    foreach($posts as $index => $post) {
      if(is_array($post)) {
        foreach($post as $key => $value) {
          echo '<',$key,'>';
          if(is_array($value)) {
            foreach($value as $tag => $val) {
              echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
            }
          }
          echo '</',$key,'>';
        }
      }
    }
    echo '</posts>';
  }

  /* reset query */
  wp_reset_postdata();
}

http://example.co.uk/json/?user=1&num=3&format=json