A
A
Andrey Yurchuk2019-08-31 22:35:10
Laravel
Andrey Yurchuk, 2019-08-31 22:35:10

What does the TokenMismatchException error mean?

Wanted to create an ajax connection on laravel something went wrong, who is good at this? Save! TokenMismatchException
The form itself

<form method="post" action="" class="my-modal-form">
                  {!! csrf_field() !!}
                    <h1>заказать</h1>
                    <div>
                        <input name="email" required type="email" placeholder="Почта">
                        <input name="name" required type="text" placeholder="Имя">
                        <input name="subm" type="submit" value="Заказать">
                    </div>
                </form>

Here jquery code and ajax
function getMessage(){
           $.ajax({
              type:'POST',
              url:'/buycoffie',
              data:'_token = <?php echo csrf_token() ?>',
              success:function(data){
                 $("input").val(data.msg);
              }
           });
        }

$ ('input[name="subm"]').on('click', function(event) {
  event.preventDefault();
  getMessage()
});

There is only one Controller. There are two routes in web.php
namespace App\Http\Controllers;

use App\Navigation;
use App\Frontle;
use App\Description;

use Illuminate\Http\Request;

class IndexController extends Controller
{
    public function run()
    {
      $nav = Navigation::all();
      $fron = Frontle::all();
      $descr = Description::all();

      return view('index', [
          'nav' => $nav,
          'fron' => $fron,
          'descr' => $descr
      ]);
    }

    public function buycoffie()
    {
      if (isset($_POST)) {
        $agv = array('msg' => 'YES!!');

        return response()->json($agv, 200);
      } else {
        return abort(404);
      }
    }
}

web.php
Route::match(['post', 'get'], '/', ['uses' => '[email protected]', 'as' => 'home']);
Route::post('/buycoffie','[email protected]');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2019-08-31
@AnDrIYQ

This means that the csrf token is not sent, you have it incorrectly written in ajax. There are examples on stackoverflow and in the documentation on how to send it correctly.
UPD. Most likely this piece is missing:

$(function () {
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question