EdwardBlack EdwardBlack - 1 month ago 17
Javascript Question

Send javascript variable value to controller action

I simply try to pass a value from javascript to a action from my controller and return the value back:

This is my controller:

<?php
namespace Black\Test\Controller;

/**
* CustomController
*/
class CustomController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{

/**
* action test
*
* @return void
*/
public function testAction()
{
$myVar = $this->request->getArgument('myVar');

echo "myVar = ". $myVar;
}
}


How do i have to setup my button to make it work?
Let's assume I try to pass over the sessionStorage Item
test
.

This is what I've tried:

<f:link.action controller="Custom" action="test" arguments="{myVar: sessionStorage.getItem('test')}" class="mbButton">Download</f:link.action>


I get:
The argument "arguments" was registered with type "array", but is of type "string" in view helper "TYPO3\CMS\Fluid\ViewHelpers\Link\ActionViewHelper


If I set the value manually e.g:

<f:link.action controller="Custom" action="test" arguments="{myVar: 1}" class="mbButton">Download</f:link.action>


Then I get
1
as response.

Answer

Generating a link with a placeholder value and then changing that placeholder value will corrupt the cHash value that gets calculated for the link. In addition, it would cause cHash collisions in this and other links using the same placeholder (resulting in identical links).

This is part of the framework and for security reasons it cannot be avoided. Provide the correct ID from within your template; create a ViewHelper to handle the storage if you need it somehow separate (but beware if you mix cached and uncached plugins then!). But best of all, make your link building follow the security rules and include the value so the cHash gets calculated and verified correctly.

In addition you have a syntax error in the arguments argument for your link:

arguments="{myVar: sessionStorage.getItem('test')}"

Will not work. If your sessionStorage is a variable, and "item" on it implements ArrayAccess or has a getter for the property "test", use:

arguments="{myVar: sessionStorage.item.test}"