0

I want to send a Ajax post request but i get some issues with CSRF.

Here is my js code :

 function sendAjaxRequest(index){
    var token = $('meta[name=csrf_token]').attr('content')
    $.ajaxSetup({ headers: { 'csrftoken' : token } });
    $.ajax({
       method: "POST",
        data: '{"value":"10"}', 
       dataType: 'json',
       url: "http://localhost/laravel/public/",
    });
 }

Here is my route from my laravel routes.php file :

Route::post('/','AjaxController@updateOrder');

Here is my console (jQuery issue) :

POST http://localhost/kaemo/public/ 500 (Internal Server Error)

Here is my network preview :

TokenMismatchException in VerifyCsrfToken.php line 67:

Any ideas ?

2 Answers 2

3

Try to set CSRF token in X-CSRF-TOKEN like,

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

And add the below code in your app/Http/Middleware/VerifyCsrfToken.php, add the tokenMatch() method to this.

<?php
    /**
     * Determine if the session and input CSRF tokens match.
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function tokensMatch($request)
    {
        // If request is an ajax request, then check to see if token matches token provider in
        // the header. This way, we can use CSRF protection in ajax requests also.
        $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

        return $request->session()->token() == $token;
    }

Read more [Laravel5] TokenMismatchException in VerifyCsrfToken

Sign up to request clarification or add additional context in comments.

Comments

1

Try putting the token into your data

var token = "{{csrf_token()}}";
$.ajax({
   method: "POST",
    data: '{"value":"10", _token: token}', 
   dataType: 'json',
   url: "http://localhost/laravel/public/",
});

1 Comment

ehh just realised that your url seems incorrect, try using only localhost/laravel ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.