Magento – How to send a form key with post data using ajax to a controller in magento

ajaxform-keymagento-1

Suppose I have an ajax function like this in a separate js file

jQuery.ajax({
    url: "/package/module/index/index",
    type: "POST",
    data: {name: user_name, dob: date_of_birth},//here i want to send a form key used in magento
    success: function(response){
        console.log(response);
    }
});

My controller is like this

Class Package_Module_IndexController extends Mage_Core_Controller_Front_Action {
    public function indexAction(){
        //stufss to do here
    }
}

In above php controller I want to validate request with a magento form key.

Best Answer

If you want to use js in external file then you need to add below code in any top of head.phtml file

var formKey = "<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>";

Then add your js code as below:

jQuery.ajax({
    url: "/package/module/index/index",
    type: "POST",
    data: {form_key:formKey name: user_name, dob: date_of_birth},//here i want to send a form key used in magento
    success: function(response){
        console.log(response);
    }
});