Laravel 5.5 ajax call 419 (unknown status)
Asked Answered
C

23

190

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.

Campbellbannerman answered 28/9, 2017 at 9:54 Comment(9)
did you have this? <meta name="csrf-token" content="{{ csrf_token() }}"> Spurtle
@HanlinWang No I don't have a form it's just a dropdown.Campbellbannerman
have you added {{csrf_field()}} in your form??Colchicum
@Mr.Pyramid I don't have a form I do the ajax call of a dropdown changeCampbellbannerman
it's not for form, you can add this meta tag inside your <head></head>Spurtle
dropdown is a part of form you need to make that request through formColchicum
or pass the csrf_token in your data like this {'_token': {{csrf_token()}}}Colchicum
Try removing the contentType and processData options from your ajaxBellbird
Check This. #49306885Dasher
S
388

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

Shalondashalt answered 28/9, 2017 at 10:15 Comment(7)
I have this exact code set up, but I am still experiencing OP's problem in the following situation: user is logged in, but the site remains idle for a long period (for example, computer goes to sleep with the browser open). In this case, when the user gets back to the computer and try an AJAX call, this error happens. After a reload, everything is back to normal. Anyone have a solution to this?Tibetan
@jovan There are two ways you can achieve that easily. Take a look at these awesome jquery libraries https://www.jqueryscript.net/other/Session-Timeout-Alert-Plugin-With-jQuery-userTimeout.html https://github.com/kidh0/jquery.idle. Secondly, On your ajax request, check if it returns an error code of 419 then redirect.Citronella
@jovan I too was struggling with this and even closing the browser, etc wouldnt fix the issue. I managed to find how to fix it though and by putting the aforementioned 'ajaxsetup()' line of code mentioned above WITHIN my post() call - the csrf token was set properly and everything started working flawlessly.Minuend
But why 419 Unknown status? Why not 419 Invalid CSRF token or some existing, useful response? Where does it come from? Why? EtcMezzorelievo
Why is this not common knowledge and recorded everywhere?Nerty
Any idea why I'm getting this error? I am actually sending the token so it's not that.Korman
Not working on SafariCampball
C
39

Another way to resolve this is to use the _token field in ajax data and set the value of {{csrf_token()}} in blade. Here is a working code that I just tried at my end.

$.ajax({
    type: "POST",
    url: '/your_url',
    data: { somefield: "Some field value", _token: '{{csrf_token()}}' },
    success: function (data) {
       console.log(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);

    },
});
Cavanaugh answered 27/12, 2017 at 6:41 Comment(1)
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},Gesticulatory
S
16

It's possible your session domain does not match your app URL and/or the host being used to access the application.

1.) Check your .env file:

SESSION_DOMAIN=example.com
APP_URL=example.com

2.) Check config/session.php

Verify values to make sure they are correct.

Stockbreeder answered 11/4, 2018 at 17:44 Comment(2)
This was the correct solution for me. Very frustrating, the HTTP 419 code does not match the HTTP spec and can mean so many things.Freeloader
doesn't work on SafariCampball
I
14

This is similar to Kannan's answer. However, this fixes an issue where the token should not be sent to cross-domain sites. This will only set the header if it is a local request.

HTML:

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

JS:

$.ajaxSetup({
    beforeSend: function(xhr, type) {
        if (!type.crossDomain) {
            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
        }
    },
});
Impose answered 14/12, 2017 at 5:2 Comment(1)
The normal header setup worked for me for a while, but randomly started having issues after months of working fine. I'm not completely sure why it began having issues out of nowhere, but this solution worked great and fixed the issue for me.Estimate
R
11

use this in your page

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

and in your ajax used it in data:

_token: '{!! csrf_token() !!}',

that is:

$.ajax({
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {
                   _token: '{!! csrf_token() !!}',
                 },
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });

Thanks.

Raymer answered 22/3, 2018 at 12:53 Comment(0)
T
8

in my case i forgot to add csrf_token input to the submitted form. so i did this HTML:

<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>

JS:

//setting containers
        var _token = $('input#_token').val();
        var l_img = $('input#l_img').val();
        var formData = new FormData();
        formData.append("_token", _token);
        formData.append("l_img", $('#l_img')[0].files[0]);

        if(!l_img) {
            //do error if no image uploaded
            return false;
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "/my_url",
                contentType: false,
                processData: false,
                dataType: "json",
                data : formData,
                beforeSend: function()
                {
                    //do before send
                },
                success: function(data)
                {
                    //do success
                },
                error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown
                {
                    if( jqXhr.status === "422" ) {
                        //do error
                    } else {
                        //do error
                    }
                }
            });
        }
        return false; //not to post the form physically
Taxeme answered 24/12, 2017 at 13:3 Comment(1)
this <input type="hidden" id="_token" value="{{ csrf_token() }}"> is necesary even if we do a submit whitouth ajax, otherwise i got a weird 419 errorNewmint
K
7

If you already done the above suggestions and still having the issue.

Make sure that the env variable:

SESSION_SECURE_COOKIE

Is set to false if you don't have a SSL certificate, like on local.

Kielty answered 2/3, 2018 at 12:10 Comment(0)
P
6

If you are loading .js from a file you have to set a variable with the csrf_token in your "main" .blade.php file where you are importing the .js and use the variable in your ajax call.

index.blade.php

...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
        var token = '{{ csrf_token() }}';
</script>

anotherfile.js

$.ajax({
    url: 'yourUrl',
    type: 'POST',
    data: {
        '_token': token
    },
    dataType: "json",
    beforeSend:function(){
        //do stuff
    },
    success: function(data) {
        //do stuff
    },
    error: function(data) {
        //do stuff
    },
    complete: function(){
        //do stuff
    }
});
Plummer answered 16/6, 2018 at 2:5 Comment(0)
P
4

2019 Laravel Update, Never thought i will post this but for those developers like me using the browser fetch api on Laravel 5.8 and above. You have to pass your token via the headers parameter.

var _token = "{{ csrf_token }}";
fetch("{{url('add/new/comment')}}", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': _token,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(name, email, message, article_id)
            }).then(r => {
                return r.json();
            }).then(results => {}).catch(err => console.log(err));
Patchwork answered 7/7, 2019 at 7:54 Comment(1)
The key 'X-CSRF-TOKEN' didn't work for me. But 'X-XSRF-TOKEN' worked.Varicelloid
C
3

Even though you have a csrf_token, if you are authenticate your controller actions using Laravel Policies you can have 419 response as well. In that case you should add necessary policy functions in your Policy class.

Composite answered 25/12, 2017 at 7:43 Comment(0)
M
3

some refs =>

...
<head>
    // CSRF for all ajax call
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
 ...
 ...
<script>
    // CSRF for all ajax call
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
...
Margay answered 15/6, 2018 at 14:56 Comment(0)
I
3

This worked for me:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
  }
});

After this set regular AJAX call. Example:

    $.ajax({
       type:'POST',
       url:'custom_url',

       data:{name: "some name", password: "pass", email: "[email protected]"},

       success:function(response){

          // Log response
          console.log(response);

       }

    });
Irrespirable answered 8/10, 2019 at 13:25 Comment(0)
R
2

You have to get the csrf token..

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

After doing same issue is rise ,Just Add this meta tag< meta name="csrf-token" content="{{ csrf_token() }}" >

After this also the error arise ,you can check the Ajax error. Then Also check the Ajax error

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});
Rehm answered 11/7, 2018 at 9:16 Comment(0)
S
2
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
Sura answered 5/4, 2019 at 20:38 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.Ganja
A
2

I had SESSION_SECURE_COOKIE set to true so my dev environment didn't work when logging in, so I added SESSION_SECURE_COOKIE=false to my dev .env file and all works fine my mistake was changing the session.php file instead of adding the variable to the .env file.

Archespore answered 5/1, 2020 at 22:15 Comment(0)
E
1

just serialize the form data and get your problem solved.

data: $('#form_id').serialize(),
Edgeworth answered 26/6, 2018 at 13:18 Comment(0)
S
0

This error also happens if u forgot to include this, in your ajax submission request ( POST ), contentType: false, processData: false,

Stylize answered 7/1, 2019 at 7:49 Comment(0)
G
0

This works great for those cases you don't require a form.

use this in header:

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

and this in your JavaScript code:

$.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
        }
    });
Gunpaper answered 28/2, 2019 at 16:13 Comment(0)
B
0

Got this error even though I had already been sending csrf token. Turned out there was no more space left on server.

Bessie answered 24/4, 2019 at 12:31 Comment(0)
C
0

A simple way to fixe a 419 unknown status on your console is to put this script inside in your FORM. {{ csrf_field() }}

Conchiferous answered 24/6, 2019 at 13:47 Comment(0)
N
0

in the name of the universe programmer

i send ajax with pure js and i understand when i dont set this method of ajax in pure js << xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") >> i recive this error 419.

the full method of pure ajax is :

let token = document.querySelector('meta[name="csrf-token"]').content;

let xhr = new XMLHttpRequest();

// Open the connection
xhr.open("POST", "/seller/dashboard/get-restaurants");

// you have to set this line in the code (if you dont set you recive error 419):

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//* Set up a handler for when the task for the request is complete
xhr.onload = function () {
    
};

// Send the data.
xhr.send(`_token=${token}`);
Nichols answered 4/7, 2022 at 20:50 Comment(0)
D
0

Just below the form field you can add @csrf like this

@csrf
Discredit answered 25/4, 2023 at 9:42 Comment(0)
R
0

If you have large data to post in to the server, please make "_token" variable as the first data.

Like below

var token = $('meta[name="csrf-token"]').attr("content");

$.ajax({
       type:'POST',
       url:'custom_url',

        data: {
        _token: token,
        property: property,
    },

       success:function(response){

          // Log response
          console.log(response);

       }

    });
Raki answered 9/7, 2023 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.