te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - TokenMismatchException in VerifyCsrfToken.php line 67 on laravel using ajax - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TokenMismatchException in VerifyCsrfToken.php line 67 on laravel using ajax - Stack Overflow

programmeradmin3浏览0评论

This view has a link which calls a javascript function

@extends('layouts.main')

@section('content')
    <table class="table">
        <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Opción</th>
        </tr>
    @foreach ($tasks as $task)
        <tr>
          <td>{{$task->id}}</td>
            <td>{{$task->name}}</td>
            <td><a href="javascript:void(0)" onclick="eliminar({{$task->id}})" class="btn btn-danger">Eliminar</a></td>
        </tr>
    @endforeach
    </table>
@stop

and here is the javascript code

function eliminar(id){
  $.ajax({

           type: "DELETE",
           url: "task/"+id,
           success: function (data) {
               console.log(data);
           },
           error: function (data) {
               alert('Error:', data);
           }
    });
}

and with the ajax call i want to call the destroy method of my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Task;

class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tasks = Task::all();
        return view('mainview',['tasks' => $tasks]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return "destroy";
    }
}

But when I click the links I get this error :

TokenMismatchException in VerifyCsrfToken.php line 67

I'm new on Laravel but I thought that csrf was for forms.

This view has a link which calls a javascript function

@extends('layouts.main')

@section('content')
    <table class="table">
        <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Opción</th>
        </tr>
    @foreach ($tasks as $task)
        <tr>
          <td>{{$task->id}}</td>
            <td>{{$task->name}}</td>
            <td><a href="javascript:void(0)" onclick="eliminar({{$task->id}})" class="btn btn-danger">Eliminar</a></td>
        </tr>
    @endforeach
    </table>
@stop

and here is the javascript code

function eliminar(id){
  $.ajax({

           type: "DELETE",
           url: "task/"+id,
           success: function (data) {
               console.log(data);
           },
           error: function (data) {
               alert('Error:', data);
           }
    });
}

and with the ajax call i want to call the destroy method of my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Task;

class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tasks = Task::all();
        return view('mainview',['tasks' => $tasks]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return "destroy";
    }
}

But when I click the links I get this error :

TokenMismatchException in VerifyCsrfToken.php line 67

I'm new on Laravel but I thought that csrf was for forms.

Share Improve this question edited Jun 6, 2016 at 17:33 Zakaria Acharki 67.5k15 gold badges78 silver badges105 bronze badges asked Jun 6, 2016 at 17:24 AFSAFS 1,4436 gold badges30 silver badges53 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

You should add csrf_field to your main blade :

{{ csrf_field() }}

Then add _token to your request :

var _token = $('input[name="_token"]').val();

function eliminar(id){
  $.ajax({
    type: "DELETE",
    url: "task/"+id,
    data: { _token : _token },
    success: function (data) {
      console.log(data);
    },
    error: function (data) {
      alert('Error:', data);
    }
  });
}

Or you could add it one time in ajaxSetup and it will affect all calls to $.ajax or Ajax-based derivatives such as $.get() :

$.ajaxSetup(
{
    headers:
    {
        'X-CSRF-Token': $('input[name="_token"]').val()
    }
});

Take a look to CSRF Protection.

Hope this helps.

This is what worked for me. I found several answers online and none of them alone worked; however, after bining all, I got the Ajax call to go through.

  1. In the head of your view file, add the following line:

    <meta name="csrf-token" content="<?php echo csrf_token() ?>"> // This will retrieve the necessary token.
    
  2. Then, retrieve the value of the token and place it on a variable (optional step):

    var currentToken = $('meta[name="csrf-token"]').attr('content');
    
  3. On your ajax call, include the value of the token in the 'data:' field:

    $.ajax({type: 'POST', data: {_token:currentToken},....});
    

You may avoid the optional step of creating a new variable to it on the 'data:' field; however, I find this step easier to understand.

Hope this helps.

You need to add the token input field when passing the 'DELETE' method.

Html:

<input class="token" value="{{ csrf_field() }}"/>

Code:

function eliminar(id){
  var formData = '_token=' + $('.token').val();
  $.ajax({
           type: "DELETE",
           url: "task/"+id,
           data: formData,
           success: function (data) {
               console.log(data);
           },
           error: function (data) {
               alert('Error:', data);
           }
    });
}

You could also remove that route from the verification process by adding it to the except array in the Middleware.

发布评论

评论列表(0)

  1. 暂无评论