ajax


Laravel 5 csrf tokens in ajax calls

In Laravel 5, all requests must pass through the Middleware which will not allow any POST requests without the correct CSRF token.

CSRF (Cross Site Request Forgery) prevents the site receiving requests from clients that it has not established a connection with. IE a random post request from a third party.

When using ajax to post form or changes in state, the csrf token must be supplied along with the request.

For instance, if the view being rendered contains the javascript, simply use blade tags to insert the token directly into the script:

                $.ajax({
                      type: "POST",
                      url: "/poke",
                      data: {   lat: lastlat,
                                lng: lastlng, 
                                bearing: 90,
                                '_token': '{!! csrf_token() !!}'
                            }
                    })

If the javascript is in a separate file (not processed by Blade) then the token can be set on a meta element and then queried by jQuery at runtime.

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

Putting the above in the master page layout ensures that the csrf token is available in every page

Referring then to the meta element in each javascript ajax request;

                $.ajax({
                      type: "POST",
                      url: "/poke",
                      data: {   lat: lastlat,
                                lng: lastlng, 
                                bearing: 90,
                                '_token': $('meta[name="csrf-token"]').attr('content')
                            }
                    })

Thanks to Kelt Dockin for inspiration