Laravel 5.5 ajax call 419 (unknown status)

Chris picture Chris · Sep 28, 2017 · Viewed 209.4k times · Source

I do an ajax call but I keep getting this error:

419 (unknown status)

No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.

my call:

$('.company-selector li > a').click(function(e) {
     e.preventDefault();

     var companyId = $(this).data("company-id");


      $.ajax({
          headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {},
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });
  });

My route:

Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');

My controller method

/**
 * Fetches a company
 *
 * @param $companyId
 *
 * @return array
 */
public function fetchCompany($companyId)
{
    $company = Company::where('id', $companyId)->first();

    return response()->json($company);
}

The ultimate goal is to display something from the response in a html element.

Answer

Kannan K picture Kannan K · Sep 28, 2017

Use this in the head section:

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

and get the csrf token in ajax:

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

Please refer Laravel Documentation csrf_token