64

I would really appreciate some help on this. I tried tons of solutions as posted in this forum, but I cannot get it to work.

My ajax call is something like

$(document).ready(function() {
    $("#company").click(function() {
        $.ajax({
            type: "POST",
            dataType:'html',
            url : "/company",
            success : function (data) {
                $("#result").html(data);
            }
        });
    });
});

I am calling the view through my route

Route::post('/company', 'Ajaxcontroller@loadContent');

And controller

public function loadContent()
    {
        return view('listing.company')->render();
    }

My company.blade.php is

    @foreach ($companies as $company)
            <div class="posting-description">
            <h5 class="header"><a href="#"></a>{{$company->name}}
            </h5>
            <h5 class="header"> {{$company->streetaddress}} {{$company->postalcode}}</h5>  
            <p class="header">
             <span class="red-text"> <?= $service; ?> </span> is available on <span class="green-text"><?php echo $date; ?></span>
           </p>
    @endforeach

I am getting this error

POST http://127.0.0.1:8234/company 419 (unknown status)
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Cowgirl
  • 1,454
  • 5
  • 19
  • 40
  • 1
    Did you know that this `@foreach` is a templating engine and not PHP ? and how it is supposed to request the database for companies if you're not calling the database, and also CSS is an interpreted language so saying *It compiles the CSS files* is incorrect! And finally, yeah you should do the logic in your controller and then pass the result of the view to be rendered to your Ajax! – teeyo Sep 28 '17 at 15:25
  • Yes, I am aware of that. It does not compile something like = $service; ?> too. How should I call the database, can you shed some light on that? – Cowgirl Sep 28 '17 at 15:29
  • You are using Laravel, an MVC framework, you need to create a route to an action in your controller in this action you will call the database using eloquent and pass the result to the view which should render back HTML. – teeyo Sep 28 '17 at 15:31
  • I am aware of that too. I tried doing that, but in my case, I pass the eloquent to my view, but that specific view needs to get access to the variable in the URL from GET method, it cannot do that. Additionally, I don't want to include the navbar and other things in that view. – Cowgirl Sep 28 '17 at 15:36
  • You create your portion of the view without extending the navbar and other componenet and you put only the loop code, I don't get it how you can't access the variable ? you pass the variable to the view, wich means it will be available in the view ! – teeyo Sep 28 '17 at 15:38
  • I tried posting the view instead of getting the view, but I get this 419 error, which does not go away ever. – Cowgirl Sep 28 '17 at 15:39
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155530/discussion-between-chris-mkp-and-teeyo). – Cowgirl Sep 28 '17 at 15:39
  • Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the [CC BY-SA 3.0 license](https://creativecommons.org/licenses/by-sa/3.0/)). By SE policy, any vandalism will be reverted. If you would like to disassociate this post from your account, see [What is the proper route for a disassociation request?](https://meta.stackoverflow.com/q/323395) – Paul Roub Sep 28 '17 at 16:24

11 Answers11

141

Laravel 419 post error is usually related with api.php and token authorization

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Add this to your ajax call

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

or you can exclude some URIs in VerifyCSRF token middleware

 protected $except = [
        '/route_you_want_to_ignore',
        '/route_group/*
    ];
Abhinav Keshri
  • 595
  • 5
  • 20
Dhiraj
  • 2,687
  • 2
  • 10
  • 34
  • Worth noting that some people change the meta name attribute. The one in the project I was working on was renamed to `_token`. – B3none May 06 '20 at 07:06
14

419 error happens when you don`t post csrf_token. in your post method you must add this token along other variables.

Adnan Rasheed
  • 866
  • 8
  • 12
3

Had the same problem, regenerating application key helped - php artisan key:generate

EXayer
  • 145
  • 1
  • 9
1

You don't have any data that you're submitting! Try adding this line to your ajax:

data: $('form').serialize(),

Make sure you change the name to match!

Also your data should be submitted inside of a form submit function.

Your code should look something like this:

<script>
 $(function () {
  $('form').on('submit', function (e) {
   e.preventDefault();
   $.ajax({
    type: 'post',
    url: 'company.php',
    data: $('form').serialize(),
    success: function () {
     alert('form was submitted');
    }
   });
  });
 });
</script>
Lulceltech
  • 1,662
  • 11
  • 22
  • Still, he does not have any logic in the controller from what I understand :) – teeyo Sep 28 '17 at 15:26
  • I mean he does have more issues beyond just the AJAX, but he's asking about the AJAX portion of it so i'm just giving him that answer :P – Lulceltech Sep 28 '17 at 15:28
1

I had the same issue, and it ended up being a problem with the php max post size. Increasing it solved the problem.

1

I received this error when I had a config file with <?php on the second line instead of the first.

eli
  • 187
  • 2
  • 15
1

You may also get that error when CSRF "token" for the active user session is out of date, even if the token was specified in ajax request.

eldorjon
  • 170
  • 2
  • 13
1

Step 1: Put the csrf meta tag in head

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Document</title>
</head>
<body>

Step 2: Use this ajax format

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
      $("#frm").submit(function(e){
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
            });
        $.ajax({
                url:"{{ url('form_submit') }}",
                data:$('frm').serialize(),
                type:'post',
                success: function(result){
                    console.log(result);
                }
        });
      });
    });
</script>
Gorka
  • 1,971
  • 1
  • 13
  • 28
  • Can you give some more explanation to your answer rather than just supplying some code. Especially since this is quite a old question and already has an question with quite a few upvotes – Richard Hpa Jul 18 '21 at 23:06
0

In laravel you can use view render. ex. $returnHTML = view('myview')->render(); myview.blade.php contains your blade code

0

In your action you need first to load companies like so :

$companies = App\Company::all();
return view('listing.company')->with('companies' => $companies)->render();

This will make the companies variable available in the view, and it should render the HTML correctly.

Try to use postman chrome extension to debug your view.

teeyo
  • 3,665
  • 3
  • 22
  • 37
  • I am doing that too, I am just using compact function to pass that companies variable to the listing.company view – Cowgirl Sep 28 '17 at 15:53
  • Well the `->render()` should render the HTML, you should get a string with HTML inside, no blade tags! I'm sorry I have no Laravel installaion available so I can debug with you. – teeyo Sep 28 '17 at 15:55
0

for me this happens now and then when running a unit test

php artisan config:clear

helped me

Witold
  • 875
  • 5
  • 5