简体   繁体   中英

TokenMismatchException in laravel 5.2 ajax call

i am getting token mismatch exception every thing is seem correct.

this is my view code

@extends('layouts.master')
@section('content')
<div class="bg"></div>
<div class="login-sec clearfix">

    <h1 class="lg-logo">YOU ARE JUST ONE STEP AHEAD</h1>
    <div class="login-box clear">

        <form id="websiteform" action="#">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <div class="col-md-12 form-field">
                <label for="">Project Name</label>
                <input type="text" name="project" id="project">
            </div>

            <div class="col-md-12 form-field">
                <label for="">Website URL</label>
                <input type="url" name="website_url" id="website_url">
            </div>

            <div class="col-md-12 form-field">
                <button type="submit" class="btn-green btn-large">Add Your Website</button>
            </div>
        </form>

    </div>
</div>
@stop

and form source head section and footer is

  <head>
   <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="csrf-token" content="4ryCSznz0mPSBcwXvbmZZHkZGcxZpyDy2dQ1VAoc" />
<link href="http://localhost:8080/css/bootstrap.min.css" rel="stylesheet" media="screen">

 <script src="http://localhost:8080/js/jquery.min.js"></script>
<script src="http://localhost:8080/js/bootstrap.min.js"></script>
<script src="http://localhost:8080/js/main.js"></script>

and my ajax call in main.js

$(document).ready(function () {

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$('#websiteform').submit(function(e){
    e.preventDefault();
    var pro=$('#project').val();
    var url=$('#website_url').val();

    $.ajax({
        type: "POST",
        url: "project_save",
        data:  {project: pro, url: url},
        success: function(data)
        {
            if(data.success==false)
            {
             alert(data.error);
            }
            else{
                window.location =  "dashboard";
            }
        },
        error:function(){}
    });
});
});

and route and controller function

 Route::post('/project_save','WebsiteController@project_save');
  public function project_save()
{
    if(Request::ajax()){

        $validator = Validator::make(Request::all(), [
            'project' => 'required|max:255',
            'url' => 'required',
        ]);
        if($validator->fails()){
            return Response::json(['success'=>false,'error'=>$validator->errors()->toArray()]);
        }

        $Website = new Website;
        $Website->project_name = Request::get('project');
        $Website->website_url = Request::get('url');
        $Website->user_id = Auth::id();
        $Website->save();
        return Response::json(['success'=>true]);
    }

}

this is my code and i am getting tokenmismatach exeption.

Change your \\App\\Http\\Middleware\\VerifyCsrfToken.php , add this code to function tokensMatch :

if ($request->ajax()) {
        return true;
    }

Try this

$_token = "{{ csrf_token() }}";
$.post( 'myurl', { param1: $param1, param2: $param2, _token: $_token })
  .done(function( data )
{
    console.log('Done!');
});

If you do not want CSRF protection for a particular url then you can add the urls in App\\Http\\Middleware\\VerifyCsrfToken.php like this

protected $except = [
    "project_save"
];

Carefully do a check on the following :

I had a similar issue and it was an easy fix.

Add this in your HTML meta tag area :

 <meta name="csrf-token" content="{{ csrf_token() }}">

Then under your JQuery reference, add this code :

<script type="text/javascript">
      $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
      });
  </script>

If you are using the HTML form submit (not AJAX) then you need to put :

{{ csrf_field() }} 

inside your form tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM