Ajax LARAVEL 419 POST error

PhpJqueryAjaxLaravel

Php Problem Overview


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)

Php Solutions


Solution 1 - Php

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/*
    ];

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

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>

Solution 5 - Php

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

Solution 6 - Php

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

Solution 7 - Php

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.

Solution 8 - Php

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

Solution 9 - Php

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.

Solution 10 - Php

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCowgirlView Question on Stackoverflow
Solution 1 - PhpDhirajView Answer on Stackoverflow
Solution 2 - PhpAdnan RasheedView Answer on Stackoverflow
Solution 3 - PhpEXayerView Answer on Stackoverflow
Solution 4 - PhpLulceltechView Answer on Stackoverflow
Solution 5 - PhpFrancisco IsidoriView Answer on Stackoverflow
Solution 6 - PhpeliView Answer on Stackoverflow
Solution 7 - PhpeldorjonView Answer on Stackoverflow
Solution 8 - PhpАлександр ВолошиновскийView Answer on Stackoverflow
Solution 9 - PhpteeyoView Answer on Stackoverflow
Solution 10 - PhpAgni Sankar ChakrabortyView Answer on Stackoverflow