24
votes

This is my test ajax in laravel 5 (refer below)

$("#try").click(function(){
    var url = $(this).attr("data-link");
    $.ajax({
        url: "test",
        type:"POST",
        data: { testdata : 'testdatacontent' },
        success:function(data){
            alert(data);
        },error:function(){ 
            alert("error!!!!");
        }
    }); //end of ajax
});

and the trigger link

<a href="#" id="try" data-link="{{ url('/test') }}">Try</a>

and my route

Route::post('test', function()
{
    return 'Success! ajax in laravel 5';
});

but it gives me an error when I run the console in google chrome and it doesn't return the expected response "return 'Success! ajax in laravel 5';"

POST http://juliver.laravel.com/test 500 (Internal Server Error)

whats wrong/problem to my code? anything I'm missing?

12

12 Answers

54
votes

While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.

Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">

And add to your javascript-file (or section within the page):

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

See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.

15
votes

90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:

  • Wrong Request Type (e.g sending post to get)
  • Wrong data type recived (e.g ajax is expecting JSON and app returns string)
  • Your .htaccess is misconfigured
  • Missing Route
  • Code Error

You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/

8
votes

I guess this has been solved by now but still the best thing to do here is to send the token with your form

{!! csrf_field() !!}

and then in your ajax

$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
    url: "test",
    type:"POST",
    data: { '_token': token, 'someOtherData': someOtherData },
    success:function(data){
        alert(data);
    },error:function(){ 
        alert("error!!!!");
    }
}); //end of ajax
});
4
votes

You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.

protected $except = [
    "your url",
    "your url/abc"
];
4
votes

In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:

class VerifyCsrfToken extends BaseVerifier {

    private $openRoutes =
    [
        ...excluded routes
    ];

    public function handle($request, Closure $next)
    {
        foreach($this->openRoutes as $route)
        {
            if ($request->is($route))
            {
                return $next($request);
            }
        }

        return parent::handle($request, $next);
    }
};

This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.

2
votes

Laravel 7.X In bootstrap.js, in axios related code, add:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');

Solved lot of unexplained 500 ajax errors. Of course it's for those who use axios

1
votes

By default Laravel comes with CSRF middleware.

You have 2 options:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array
1
votes

for me this error cause of different stuff. i have two ajax call in my page. first one for save comment and another one for save like. in my routes.php i had this:

Route::post('posts/show','PostController@save_comment');
Route::post('posts/show','PostController@save_like');

and i got 500 internal server error for my save like ajax call. so i change second line http request type to PUT and error goes away. you can use PATCH too. maybe it helps.

1
votes

you have to pass the csrf field through ajax please look at the code here

$.ajax({
                                        type: "POST",
                                        url:'{{URL::to("/delete-specialist")}}',
                                        data: {
                                            id: id,

                                            _token: $('#signup-token').val()
                                        },
                                        datatype: 'html',
                                        success: function (response) {
                                            if(response=="deleted"){
                                                $("#"+id).hide();
                                                $("#message").html("successfully deleted");
                                            }

                                        }

                                    });

and you also need to write this input field before this

<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">

still if you do not understand please enjoy this video https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s

1
votes

Using post jquery instead helped me to solve this problem

$.post('url', data, function(response) {
    console.log(response);
});
1
votes

Short and Simple Solution

e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
/* the route pointing to the post function */
    url: url,
    type: 'DELETE',
/* send the csrf-token and the input to the controller */
    data: {message:value},
    dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
    success: function (data) { 
    console.log(data)
    //$('.writeinfo').append(data.msg);
    //$('#ruleRow'+id).remove();
    }
});
return false;
0
votes

do not forget add "use Illuminate\Http\Request;" on your controller