2
votes

To pull partial views dynamically in laravel, you would use ajax. From a security standpoint, you would normally use a token that laravel provides to avoid csrf attacks. Many times, you don't need an entire HTML form, you just use jquery to post data, so you can retrieve a partial view as a response, and inject it into your HTML.

I understand that in an HTML form, you can include a token for laravel to avoid csrf, but if it's an ajax request via jquery without a form, and you have many elements on the same page doing different things via ajax on their individual click events for example, do you need multiple different tokens for each when you do the post to protect yourself from csrf attacks, or can you create a single global line in HTML like:

<div style="display: none;" data-token="{{ csrf_token() }}">

In a certian area on the page, that you can use for all your non-form ajax requests when you write jquery post request for. What I am asking is, for non form element jquery post requests, can you use a single data-token attribute, or should each non form jquery element have its own csrf_token data attribute sent to the route to prevent a csrf attack?

1
Duplicate of: stackoverflow.com/questions/14715250/… Do note that laravel will generate the same csrf_token for each session. Which means regardless of how many forms you have, even if you refresh the page, the csrf_token will have the same value as long as the session is not expired. If you want, you can generate your own but you will have to load it and validate it before it does it own.turntwo

1 Answers

4
votes

Try to create a global variable in javascript that will hold the current value of _token, you can add this code to your html header

<script> var _token = '<?php echo csrf_token(); ?>'; </script>

then put that _token to each ajax request

(assuming that you filtered the route with csrf checking)