Support the ongoing development of Laravel.io →
Views Forms Installation

Hi!

I am generating an edit form of an object, that is returned by Ajax. Everything's fine, but I have really clue of, how to generate csrf_token for that form. Any ideas?

I tried getting the token along with the object data I am getting, by

    \Session::get('_token');

but that seems to be incorrect, as after the form is generated, laravel gets a new token I guess.

Here's the form generated:

$("#memory").html('\
<div class="form container" id="editForm">\
    <form class="form-group" action="/editMemory/'+id+'" method="POST" enctype="multipart/form-data" >\
        <div class="form-group">\
            <textarea class="form-control" name="memory">'+ memoryObj.memory +'</textarea>\
            <input class="form-control"type="file" name="photo" id="photo">\
            <meta name="csrf_token" content="'+memoryObj.token+'">\
            <button class="btn btn-primary" type="submit">Edit Memory</button>\
        </div>\
    </form>\
    <form class="form-group" action="/deleteMemory/'+id+'" method="POST" >\
        <div class="form-group">\
            <button class="btn btn-default" type="submit" id="deleteMemory">Delete Memory</button>\
            <meta name="csrf_token" content="'+memoryObj.token+'">\
        </div>\
    </form>\
</div>\
<div class="btn btn-danger" onclick="getMemory(' + memoryObj.id + ')">Cancel</div>');
Last updated 2 years ago.
0
Solution

I solved this actually.:

I put:

<input type="hidden" id="csrf_token" value="{{ csrf_token() }}"/>

in the view where the form is rendered.
Then I pulled out the value in js :

csrf_token = document.getElementById('csrf_token');

and put it in the form like this:

<input type="hidden" name="_token" value="'+csrf_token.value+'">\
Last updated 8 years ago.
0

How about sending it as a cookie? And then use a filter to check this cookie? If you mark your cookie as HTTP secure, then all request will send this. And you don't need to JavaScript worry about it.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

seki98 seki98 Joined 23 Aug 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.