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.

4

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);
    }
});
0

Hi you need to call form key block like below in form html:

<?php echo $this->getBlockHtml('formkey'); ?>

For passing it in ajax call you can defined form serialize in data parameter of ajax call:

jQuery.ajax({
url: "/package/module/index/index",
type: "POST",
data: jQuery('#Your_form_id').serialize() + "&name="+user_name+"&par2="+date_of_birth
success: function(response){
    console.log(response);
}
});

need add username and dob additionally only if both are not defined in form.

0

Try using this,

jQuery("#form_id").on("submit", function(event) {
jQuery.ajax({
    url: "/package/module/index/index",
    type: "POST",
    data: jQuery(this).serialize(),//here i want to send a form key used in magento
    success: function(response){
        console.log(response);
    }
});
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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