Quantumass soufiane
Quantumass soufiane

Reputation: 13

MethodNotAllowedHttpException - CSRF -laravel 5.2

I'm using ajax to post a request then it refresh a part of the site with jquery function "load" and it's working good but when I try to redo this post it says MethodNotAllowedHttpException I think the problem in laravel csrf protection because after I refresh the whole page it works fine my problem is how can I save the csrf token even if I refresh a part of site ? ** thanks in advance ** (ᵔᴥᵔ)

these are the Routes

Route::post('/upvote', array(
  'uses'=> 'AffichageController@upvote',
  'as'=> 'upvote' ));

Route::post('/putcomment', array(
  'uses'=> 'AffichageController@putcomment',
  'as'=> 'putcomment'));

I think the problem is not in the routes because it works fine but when ajax loads a part of the website it stops working, this is how I load only part of site $("#partOfSite").load('theURLofSITE #partOfSite')

if I reload the page it turns to work again

Upvotes: 0

Views: 444

Answers (3)

Quantumass soufiane
Quantumass soufiane

Reputation: 13

I solved the problem, as Mr @Gadzhev said is not problem with csrf verification it is problem with route.

the route is defined in the ajax function but not in the form so when I do load with jquery the form forget that there is a function that execute this form and start to submit the form without ajax so it cause this problem and it means the routes is wrong.

so to solve this problem just reload the ajax function with the div you want to load.or if you are using function trigger like that

$('.button').on('click',function(){alert('clicked')})

change it to :

$('body').on('click','.button',function(){alert('clicked')})

here are some questions that may help you :

Jquery Event won't fire after ajax call

why does jquery's .load() ignore <script>?

Upvotes: 0

Gadzhev
Gadzhev

Reputation: 442

Can you show your routes? The error exception for missing CSRF token is usually TokenMismatchException. MethodNotAllowedHttpException indicates that there's something wrong with the routes.

Either the route is not defined or you're not passing the correct verb. Here's an example AJAX call for the PUT method:

function myAjaxCall() {

    var formData = {
        '_method': 'PUT'
        // Some other data you want to pass to your controller
    }

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

    $.ajax({
        url: url,
        type: "POST",
        data: formData,
        success: function (response) {
            // Your login on success
        },
        error: function (response) {
            // Handle error
        }
    });
}

Upvotes: 1

Smith Mike
Smith Mike

Reputation: 23

It is usually recommended to pass the csrf token to the web-page in meta tags (which are inside <head></head> tags)

 <meta name="_token" content="{{  csrf_token() }}" />

Upvotes: 1

Related Questions