I wrote the following code to generate a form in JavaScript and transition to another screen.
var form = $('<form />', {'action': /Controller/Action, 'method': 'post'});
form.append($('<input />', {'type': 'hidden', 'name': 'id', 'value': id }));
form.append($('<input />', {'type': 'hidden', 'name': '_csrfToken', 'value': $.cookie('csrfToken') }));
form.appendTo(document.body);
form.submit();
However, it will result in ’ CSRF token mismatch.’ error.
The submitted form data contains _csrfToken correctly, what is the problem?
I have a similar problem, i solved it using:
<?php echo $this->Form-create(); :>
and
<?php echo $this->Form->end(); ?>
Note that the “Form” is starting with capital letters. If tiny doesn’t work.
Thanks.
But I know how to do it, and I do it on another controller/view.
What I want to do is generate and submit a form purely in JavaScript.
Zuluru
September 13, 2019, 3:06pm
4
When you use the form helper, additional hidden fields are created. If you want to make a form on the fly, you’ll need to replicate that as well.
There is a better way to do it.
In your controller:
public function generateform()
{
$this->viewBuilder()->enableAutoLayout(false);
//More logic here if required, use $this->render() later.
$this->response->withStringBody($renderedView);
}
and generate the form in your view file via an ajax GET call.
Using this method you can even customize it I use this method when clients do not want re-captcha and I can perform various cookie exchange in the process.
1 Like
deanoj
September 17, 2019, 12:00pm
6
You will need to fetch the token from the server initially and store it client side, you can then use it in future POST requests as required.
This is the same approach when using CSRF tokens with JSON APIs for a mobile device.
1 Like