CSRF token mismatch that form send by JavaScript

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

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.

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.

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()
    //More logic here if required, use $this->render() later.

and generate the form in your view file via an ajax GET call.

Using this method you can even customize it :slight_smile: I use this method when clients do not want re-captcha and I can perform various cookie exchange in the process.

1 Like

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