Anjali Mirani
Anjali Mirani

Reputation: 65

TokenMismatchException in VerifyCsrfToken.php line 53

i made a page view/maessage.php
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">

  <script>
     function getMessage(){
        $.ajax({
           type:'POST',
           url:'/getmsg',
           data:{'_token': '{{ csrf_token() }}'},
           success:function(data){
              $("#msg").html(data.msg);
           }
        });
     }
  </script>   
  <body>
   <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div>
  <?php
     echo Form::button('Replace Message',['onClick'=>'getMessage()']);
  ?>
  </body>

in routes.php

Route::get('/ajax',function(){
  return view('message');
});

Route::post('/getmsg','AjaxController@index');

in AjaxController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AjaxController extends Controller
{
   public function index(){
  $msg = "This is a simple message.";
  return response()->json(array('msg'=> $msg), 200);
   }
}

when i ran http://localhost:8000/ajax http://localhost:8000/getmsg generate below error

Whoops, looks like something went wrong.

1/1 MethodNotAllowedHttpException in RouteCollection.php line 218: in RouteCollection.php line 218 and buch of error.....

but when i saw in consol it show below error

TokenMismatchException in VerifyCsrfToken.php line 53: in VerifyCsrfToken.php line 53

i can't understand error .i am fresher in laravel. and i aactually don't know the meaning of '_token': '{{ csrf_token() }}' in message.php. pls. help to solve this error.

Upvotes: 0

Views: 757

Answers (1)

Christophvh
Christophvh

Reputation: 13224

This exception:

MethodNotAllowedHttpException

is telling you that the method on your form is not the same as the method on your route.

So you have 2 options to solve this issue.

First option : Change route method type Your route has a GET

Route::get('/ajax',function(){
  return view('message');
});

but your form has a POST

so change it to:

Route::post('/ajax',function(){
  return view('message');
});

Second option: change your ajax-form method type

Route::get('/ajax',function(){
  return view('message');
});


  <script>
     function getMessage(){
        $.ajax({
           type:'GET',
           url:'/getmsg',
           data:{'_token': '{{ csrf_token() }}'},
           success:function(data){
              $("#msg").html(data.msg);
           }
        });
     }
  </script> 

Regarding your question about CSRF . It protects against Cross Site forgery. You can read about it here: https://laravel.com/docs/5.4/csrf

Upvotes: 1

Related Questions