Adding CSRFToken to Ajax request | ajax csrf token
Ihadthisprobleminalistofpostinablog,thepostareinaviewinsideaforeach,thenisdifficultselectitinjavascript,andtheproblemofpostmethodandtokenalsoexists.Thisthecodeforjavascriptattheendoftheview,Igeneratethetokeninjavascriptfunctióninsidetheviewandnotinaexternaljsfile,theniseasyusephplavareltogenerateitwithcsrf_token()function,andsendthe"delete"methoddirectlyinparams.YoucanseethatIdon´tuseinvarroute:{{route(post.destroy,$post->id}}becauseIdon´tknowtheidIwantdeleteuntilsomeoneclickindestroybutt...
I had this problem in a list of post in a blog, the post are in a view inside a foreach, then is difficult select it in javascript, and the problem of post method and token also exists.
This the code for javascript at the end of the view, I generate the token in javascript functión inside the view and not in a external js file, then is easy use php lavarel to generate it with csrf_token() function, and send the "delete" method directly in params. You can see that I don´t use in var route: {{ route(post.destroy, $post->id}} because I don´t know the id I want delete until someone click in destroy button, if you don´t have this problem you can use {{ route(post.destroy, $post->id}} or other like this.
$(function(){ $(".destroy").on("click", function(){ var vid = $(this).attr("id"); var v_token = "{{csrf_token()}}"; var params = {_method: DELETE, _token: v_token}; var route = "http://imagica.app/posts/" + vid + ""; $.ajax...