How to add the CSRF field to a form generated with

2019-08-24 06:15发布

问题:

Laravel requires you to write your form like this.

<form method ="POST" action="whatever">
    {{ csrf_field() }} 
</form>

I've already created around 15 forms with jquery in my website with code like the following.

$("#formholder).append("<form id='myForm' method='post' action ='whatever'></form>");

My Question is:

How do I add the csrf field on these forms created with jquery?

回答1:

Put this meta tag into the main Blade template with other meta tags:

<meta name="csrf-token" content="{{ csrf_token() }}">

Then you'll be able to access it with this from JS:

$('meta[name="csrf-token"]').attr('content')

https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token



回答2:

Alternatively: Add following input field.

<input name="_token" value="{{ csrf_token() }}" type="hidden">

to the form

Updated: In your JQuery

'....../><input name="_token" value="'+csrf_js_var+'" type="hidden"><......'

Initial Global Var or create when new blade initialized using <script> tag. Add following code inside that script tag and use the variable in your JQuery.

var csrf_js_var = "{{ csrf_token() }}" //I have used this way


回答3:

Step 1 : Add the following code to your main layout file.

<meta name="csrf-token" content="{{ csrf_token() }}">

Step 2 : Get the value of csrf token in your javascript.

var csrfVar = $('meta[name="csrf-token"]').attr('content');

Step 3 : In your form append a hidden input field with value set to your csrf variable

$("#myForm").append("<input name='_token' value='" + csrfVar + "' type='hidden'>");

This has been worked for me.