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

Get form_key

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$key_form = $objectManager->get('Magento\Framework\Data\Form\FormKey');
$form_Key = $key_form->getFormKey(); 
?>

Javascript code

<a href="javascript:;" onclick="Test()">Javascript</a>
<script type="text/javascript">
  function Test(){

          var request_data = 'id=125&form_key=<?php echo $form_Key; ?>';

          var xhttp = new XMLHttpRequest();
           xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var data = JSON.parse(this.responseText);
                var url = data.redirect;
                if(url!=''){
                  window.location.href = data.redirect;
                }
            }
          };

          xhttp.open("POST", "your_path", true);
          //xhttp.setRequestHeader("Content-type", "application/json");
          xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xhttp.send(request_data);
  }
</script>

ccontroller code

<?php
namespace Vendor\ModuleName\Controller\Login;

class Test extends \Magento\Framework\App\Action\Action
{



    protected $_customer;
    protected $_customerSession;

    public function __construct(
    \Magento\Framework\App\Action\Context $context, 
    \Magento\Customer\Model\Customer $customer,
    \Magento\Customer\Model\Session $customerSession
    )
    {

        $this->data = $_REQUEST;
        print_r($this->data);
        $this->_customer = $customer;
        $this->_customerSession = $customerSession;
        return parent::__construct($context);
    }




    public function execute()
    {
        print_r($_REQUEST);

        echo '1';
        die();

    }
}
?>

Please check it will help you. Thanks.

0

First: Add form_key from template file

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

Second: add form key to param

var formKey = jQuery('#Your_form_id').value;
jQuery.ajax({
    url: "/package/module/index/index",
    type: "POST",
    data: {name: user_name, dob: date_of_birth, form_key:formKey},
    success: function(response){
        console.log(response);
    }
});

Third: Get form key from pram (I think you know :) )

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.