Ajax in Magento

There are some instances when we are required to use Ajax features in Magento.

Prototype javascript library used in Magento has inbuilt functionality for Ajax.

I am describing here the basic method to use ajax.

I have used version 1.6.0.0 of Magento.

I am using the existing Contacts module for explanation, you can make any new module or use any of your local module.

This code will generate the hash of the Text inserted into Name field of Contacts Form

1) Override existing controller app/code/core/Mage/Contacts/controllers/IndexController.php or you can use the same file

Paste the below mentioned code into that file inside the class

 public function hashAction()
    {
    	$name = $this->getRequest()->getParam('name');    
    	
    	if(!empty($name))
		{				
			$name = trim($name);							
			echo md5($name);			
		}else
		{
			echo 'n';
		}
    }

2) Now copy the directory app/design/frontend/base/default/template/contacts (including the file form.phtml 🙂 ) and paste it in into app/design/frontend/default/default/template

3) Copy the below shown commented code into app/design/frontend/default/default/template/contacts/form.phtml
Also check I have added the event ‘onkeyup’ in Name input text box.

	    <li class="fields">
                <div class="field">
                    <label for="name" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Name') ?></label>
                    <div class="input-box">
                        <input name="name" id="name" title="<?php echo Mage::helper('contacts')->__('Name') ?>" value="<?php echo 

$this->htmlEscape($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" onkeyup="md5_hash_get('<?php echo 

$this->getUrl('contacts/index/hash'); ?>',this.value)" />
                    </div>
                </div>  
            </li>
            <!-- copy only this code-->
            <!--start-->		
            <li>
            <div class="field">
                    <label for="namehash" class="required">Hash:</label>
                    <div class="input-box" id="nh"></div>
                </div>
            </li>     
            <!--end-->

4) Also copy the below mentioned javascript code at the end of the file. Please not Here I have showed two functions , one using GET method and other using POST method. Both will give the same result, you simply need to change the function in ‘onkeyup’ event

<script type="text/javascript">
//<![CDATA[
    var contactForm = new VarienForm('contactForm', true);
//]]>
function md5_hash_get(url,val)
{	
	if(val.replace(/\s/g,"") == '')
	{	
		alert('Invalid Request');																			
	}else
	{		
		url = url+'name/'+val;
		new Ajax.Request(url, {
		  method: 'get',		  
		  onComplete: function(req) {		
		  									  
  				if(req.responseText == 'n')
				{
					alert('Invalid Request');
				}else{
					$('nh').innerHTML = req.responseText;					
				}
		  }
		});
	}
}
function md5_hash_post(url,val)
{	
	if(val.replace(/\s/g,"") == '')
	{	
		alert('Invalid Request');																			
	}else
	{		
		new Ajax.Request(url, {
		  method: 'post',
		  parameters: { name: val },
		  onComplete: function(req) {		
		  									  
  				if(req.responseText == 'n')
				{
					alert('Invalid Request');
				}else{
					$('nh').innerHTML = req.responseText;					
				}
		  }
		});
	}
}
</script>

This is how it will look

contacts
contacts

Thats it you are done, hope this will clear the idea about using Ajax in Magento .

14 thoughts on “Ajax in Magento

  1. Thanks a lot for the tutorial, it is indeed very helpful. Do you happen to know if this will work for Magento 1.8 and higher? Will appreciate some advice. Thanks!

  2. Thank you very much for the information, it is indeed very helpful. Could you please advise if the same code will work for the newest Magento versions 1.9 and 1.14? Thanks a lot!

  3. Hi,

    Your tutorial seems to be the only one trying to explain the basics, can you please point me in some direction regarding how to add an item to wishlist form category page or product page using ajax. Same for comparison list.

    And i want to do the same for Cart operations as well, but let’s just start from the wishlist.

    I’ll be really thankful to you.

  4. Hello sir i am very new to Magento so i am not being able to understand your given information correctly although it’s very useful for me so i request you to also add path of file and also where exactly we can implement the code given by you.

    Thanks
    Ne…

    1. @ne – I have already given the path, can you tell me with what part are you finding difficulty ? , so I can help further

  5. Hi there

    I’m trying to understand how to create a fresh module that may do something as simple as ‘adding’ numbers together (something like that shown in http://www.standards-schmandards.com/exhibits/ajax/). I think I understand the module creation (thanks to http://www.webspeaks.in/2010/07/create-your-first-magento-module.html) but am stuck on how the various files interact to get it working correctly.

    Are you able to adapt your tutorial to explain this to me?

    Thanks in advance

    – michael

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top