Gordova
Gordova

Reputation: 347

Get form_key with javascript in Magento 2.0?

I would like to create a custom login page from outside Magento. To do so I need to get the form_key.

How can I get the current form_key using javascript and/or PHP from outside Magento?

Notes:

I am willing to add a PHP file inside Magento to generate the for_key (but I don't know what to write and where to place it).

I am new to Magento.

I am running Magento 2.0.

I came up whit this solution. But please find me a better one!

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Get the form key</title>
<script>

window.onload=function(){

/* Get form_key from Magento */
var ajax = new XMLHttpRequest();
ajax.open("POST", "/", false);
ajax.send();
document.getElementById('hidden_div').innerHTML = ajax.responseText;
var the_form_key = document.getElementsByName("form_key")[0].value;

alert(the_form_key);

};

</script>
</head>
<body>

<div id="hidden_div" style="display:none"></div>

</body>
</html>

Upvotes: 3

Views: 9560

Answers (2)

Daniel Ifrim
Daniel Ifrim

Reputation: 287

There is an example in: vendor/magento/module-checkout/view/frontend/web/js/sidebar.js

define([
    'jquery',
    ..
    'mage/cookies'
'form_key': $.mage.cookies.get('form_key')

I see in admin (backend namespace) that there are many calls to window.FORM_KEY

Upvotes: 6

likemusic
likemusic

Reputation: 198

For frontend area use the jQuery.cookie plugin which is a part of Magento 2:

var $formKey = jQuery.cookie('form_key');

For adminhtml area use FORM_KEY JavaScript constant:

var $formKey = FORM_KEY;

Upvotes: 8

Related Questions