user3732216
user3732216

Reputation: 1589

Ajax and Laravel

I'm trying to find out why I keep getting a 500 server error on this. I have it set up correctly in my routes as I've provided and all I'm doing is returning the string haha just to see if it hits the route.

Route::post('roster/getRosterMembers', ['as' => 'roster.getRosterMembers', 'uses' => 'RosterMembersController@getRosterMembers']);

(function(document, window, $) {
    $('#type_id').change(function() {
        var type = $(this).val();
        $.ajax({
            method: 'POST',
            url: "/roster/getRosterMembers",
            token: '{{ csrf_token() }}'
        })
        .success(function( data ) {
            if ( console && console.log ) {
                    console.log( "Sample of data:", data.slice( 0, 100 ) );
            }
        })
        .error(function() {
            alert('Hello');
        });
    });


})(document, window, jQuery);

public function getRosterMembers() {
    return 'haha';
}

Upvotes: 2

Views: 91

Answers (2)

aceraven777
aceraven777

Reputation: 4556

Since you're using jQuery you can insert these codes in your view files:

Insert these between

<meta name="csrf-token" content="{{ csrf_token() }}">

Insert this script:

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

This will automatically insert CSRF token in the headers of all of your AJAX calls

From: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token

Upvotes: 0

tptcat
tptcat

Reputation: 3961

Instead of token: '{{ csrf_token() }}' it's _token: '{{ csrf_token() }}'. Note the _.

Upvotes: 2

Related Questions