Adding CSRFToken to Ajax request

后端 未结 9 2130
夕颜
夕颜 2020-11-27 05:40

I need to pass CSRFToken with Ajax based post request but not sure how this can done in a best way. Using a platform which internally checking CSRFToken

9条回答
  •  醉酒成梦
    2020-11-27 06:14

    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({
             type: "POST",
             url: route,
             data: params
        });
       });
      });
    

    and this the code of content in view (inside foreach there are more forms and the data of each post but is not inportant by this example), you can see I add a class "delete" to button and I call class in javascript.

          @foreach($posts as $post)
              
    @endforeach

提交回复
热议问题