Ajax LARAVEL 419 POST error - php

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">{{$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)

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

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

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

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>

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

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

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.

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>

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

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.

for me this happens now and then when running a unit test
php artisan config:clear
helped me

Related

Laravel 5.3 Ajax - Retrieve data sent in the ajax request from the controller

index.html
<form id="my-form">
<select id="my-select">
<option value="1">Tom</option>
<option value="2">Jerry</option>
</select>
<input type="submit" value="send data!">
</form>
Controller.php
public function getValue(Request $request)
{
return User::find($request->input('select_id'));
}
ajax.js
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var showUser = $('#show-user');
$('#my-form').on('submit', function () {
var select_id = $('#my-select').val();
$.ajax({
method: "POST",
url: "ajax",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
"select_id": select_id
},
error: function (data) {
//something went wrong with the request
alert("Error");
},
success: function (data) {
inner = "";
data.forEach(function (el, i, array) {
inner += "<div>" + el.name + "</div>";
});
showUser.html(inner);
}
});
event.preventDefault();
});
});
web.php
Route::post('ajax','Controller#getValue');
Update:
#Mahdi Youseftabar -> Thanks for it, according to the documentation I should use input() to get the request!
Problem 1: Error: 500 (TokenMismatchException);
What I did?
Add meta to :
<meta name="csrf-token" content="{{ csrf_token() }}">
I set the headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
...
headers: {
'X-Auth-Token' : token
},
...
});
What I need to do?
Retrieve the id sent in the ajax request from the controller [SOLVED]
Validate the token by the ajax request** Error 505 (Problem 1) [SOLVED]
Return from the controller is Empty [SOLVED]
Output the Users into the <div class="showUser"></div> [SOLVED]
Github Documentation of my project:
(Many to many relationships - Laravel 5.3, Ajax)
https://github.com/39ro/StudentSchoolProject
your problem is in route :
Route:post('ajax','Controller#getValue');
you use post method in your jQuery but in route you define that route method 'get' ...
in this case when you request with ajax, laravel respond you a empty response
another issue is in getting your user_id from request, you should use this in your controller:
return User::find($request->input('user_id');
Two things check
In js
data: {"userid" : userid}
method: "POST",
in controller
$value_select = User::where($request->userid)->first();
return $value_select;
Now check the response and tell me if it works
If you don't get an error, and the result is null then you probably missing something.
Remember that find() function you use in your controller is searching for primary key only.
And its an ajax request so you wont see it in the browser. To see the return value you should look in the
Developer tools > Network > and then find the request to see the
preview and response
Add relationship to Controller.php
My problem was the relationship with the other two table.
I update my main Question with the link to my GitHub Project, where I applied all your suggestions! Thanks everyone, I solved it!
For the token I solved adding what I showed in Ajax.js.
And to retrieve the data from the relationship I just make it:
public function getValue(Request $request)
{
return User::find($request->input('select_id'))->relationship_table;
}

Laravel 5.2 ajax returns 500 Internal Server Error

My question has been asked and answered here :
ajax post in laravel 5 return error 500 (Internal Server Error)
But the problem still exists for me.
//master.blade.php
<!DOCTYPE html>
<html>
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}">
...
</head>
And create inherits admin that inherits master
//create.blade.php
#extends('admin')
#section('head_scripts')
<script>
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
$('#country_id').change(function(){
$('#province_id').find('option').remove().end();
$('#province_id').attr('disabled', true);
$('#city_id').find('option').remove().end();
$('#city_id').attr('disabled', true);
var cid=$(this).val();
var params={"type":1, "country_id":cid};
var paramsString=JSON.stringify(params);
console.log(paramsString);
$.ajax({
url:'/company/ajax',
type:'POST',
data:{json: paramsString},
dataType:'json',
success:function(result){
console.log(result);
$('#provinceSelectContainer').html(result);
}
});
});
});
And in the controller :
public function ajax(string $params){
if(!$params) return null;
$params=json_decode($params);
return ($params);
}
And the route :
Route::group(['middleware' => ['auth:api']], function() {
Route::post('/company/ajax', 'CompanyController#ajax');
});
Any idea?
In the Laravel 5.2, the middleware has web, api, and auth.
If you want to use ajax sent data, you will use the api middleware with token.
You can see this reference: https://mattstauffer.co/blog/multiple-authentication-guard-drivers-including-api-in-laravel-5-2
Route::group(['middleware' => ['auth:api']], function () {
Route::post('api', someController#indexAjax');
});

ajax not working

I have following code in my view
$(document).ready(function(){
$("#mySelect").on('change', function () {
$.ajax({
url: 'list-of-product-one',
type: "get",
data: {'id':$(this).val()},
success: function(data){
console.log(data);
}
});
<select class="form-control" id="mySelect" name="cat_id" >
#foreach($category_list as $data)
<option value="{{$data->id}}">{{$data->cat_name}}</option>
#endforeach
</select>
and in my controller
public function ProductListGet(Request $request)
{
$category_list=Category::all();
$list_of_product=Product::where('cat_name','=',$request->id)->get();
return view('manager/list_of_product',['list_of_product'=>$list_of_product,'category_list'=>$category_list]);
}
if I run that then it throws an error in my web browser console like
GET XHR http://localhost/poet/public/manager/list-of-product-one [HTTP/1.0 500 Internal Server Error 156ms]
so I changed return in my controller like
return json_encode($list_of_product);
then it displays the json array in my console even if return without
$list_of_product=Product::where('cat_name','=',$request->id)->get();
this condition then it will return whole page
now my question is suppose if I have condition in my controller then how can I return my view ?
GET XHR http://localhost/poet/public/manager/list-of-product-one [HTTP/1.0 500 Internal Server Error 156ms]
Looks like you forgot send the _token. Add the following meta tag into the header section:
<meta name="csrf-token" content="{{ csrf_token() }}">
Now, send the token into the ajax request:
$(document).ready(function(){
// here you prepare the token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#mySelect").on('change', function () {
$.ajax({
url: 'list-of-product-one',
type: "get",
data: {'id':$(this).val()},
success: function(data){
console.log(data);
}
});
this condition then it will return whole page
In other hand, you should check your view content because the use of #extends('layout') makes return the content of the entire template. Just put html's markup as simple without extending the template.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

This is my test ajax in laravel 5 (refer below)
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { testdata : 'testdatacontent' },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
and the trigger link
Try
and my route
Route::post('test', function()
{
return 'Success! ajax in laravel 5';
});
but it gives me an error when I run the console in google chrome and it doesn't return the expected response "return 'Success! ajax in laravel 5';"
POST http://juliver.laravel.com/test 500 (Internal Server Error)
whats wrong/problem to my code? anything I'm missing?
While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.
Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">
And add to your javascript-file (or section within the page):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.
90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:
Wrong Request Type (e.g sending post to get)
Wrong data type recived (e.g ajax is expecting JSON and app returns string)
Your .htaccess is misconfigured
Missing Route
Code Error
You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/
I guess this has been solved by now but still the best thing to do here is to send the token with your form
{!! csrf_field() !!}
and then in your ajax
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.
protected $except = [
"your url",
"your url/abc"
];
In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:
class VerifyCsrfToken extends BaseVerifier {
private $openRoutes =
[
...excluded routes
];
public function handle($request, Closure $next)
{
foreach($this->openRoutes as $route)
{
if ($request->is($route))
{
return $next($request);
}
}
return parent::handle($request, $next);
}
};
This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.
Laravel 7.X
In bootstrap.js, in axios related code, add:
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
Solved lot of unexplained 500 ajax errors.
Of course it's for those who use axios
By default Laravel comes with CSRF middleware.
You have 2 options:
Send token in you request
Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array
for me this error cause of different stuff.
i have two ajax call in my page.
first one for save comment and another one for save like.
in my routes.php i had this:
Route::post('posts/show','PostController#save_comment');
Route::post('posts/show','PostController#save_like');
and i got 500 internal server error for my save like ajax call.
so i change second line http request type to PUT and error goes away.
you can use PATCH too.
maybe it helps.
you have to pass the csrf field through ajax please look at the code here
$.ajax({
type: "POST",
url:'{{URL::to("/delete-specialist")}}',
data: {
id: id,
_token: $('#signup-token').val()
},
datatype: 'html',
success: function (response) {
if(response=="deleted"){
$("#"+id).hide();
$("#message").html("successfully deleted");
}
}
});
and you also need to write this input field before this
<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">
still if you do not understand please enjoy this video
https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s
do not forget add "use Illuminate\Http\Request;" on your controller
Short and Simple Solution
e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: url,
type: 'DELETE',
/* send the csrf-token and the input to the controller */
data: {message:value},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data)
//$('.writeinfo').append(data.msg);
//$('#ruleRow'+id).remove();
}
});
return false;
Using post jquery instead helped me to solve this problem
$.post('url', data, function(response) {
console.log(response);
});
I had same problem. In my case, issue arise because my id field of table (in database) was not set to auto increment. When I set it to auto increment then it started working.

laravel TokenMismatchException in ajax request

i'm using resource group and use this filter to resolve TokenMismatchException problem:
Route::filter('csrf', function($route, $request) {
if (strtoupper($request -> getMethod()) === 'GET') {
return;
// get requests are not CSRF protected
}
$token = $request -> ajax() ? $request -> header('X-CSRF-Token') : Input::get('_token');
if (Session::token() != $token) {
throw new Illuminate\Session\TokenMismatchException;
}
});
my route :
Route::group(array('prefix'=> 'admin', 'before' => 'csrf'), function(){
Route::resource('profile' , 'ProfileController', array('as'=>'profile') );
});
now. i get error to Ajax requests such as this code:
<script type="text/javascript">
$(document).ready(function() {
$('#frm').submit(function(e){
e.preventDefault();
name = $('#name').val();
family = $('#family').val();
email = $('#email').val();
currPassword = $('#currPassword').val();
password = $('#password').val();
password_confirmation = $('#password_confirmation').val();
$.post("{{ route('admin.profile.update', $profile->id) }}",
{
_method : 'PUT',
name : name,
family : family,
email : email,
currPassword : currPassword,
password : password,
password_confirmation : password_confirmation
},
function(data)
{
alert(data.errors.name);
},'json');
return false;
});
});
</script>
ERROR:
{"error":{"type":"Illuminate\\Session\\TokenMismatchException","message":"","file":"\/var\/www\/alachiq\/app\/filters.php","line":83}}
i think i'm must be sent _token in $.post. but i can not get input tag with name attribute. iget this error:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
There is a tip in the Laravel docs on how to do this. This might not have been available at the time of the question, but I thought I would update it with a answer.
http://laravel.com/docs/master/routing#csrf-x-csrf-token
I have tested the meta tag method from the documentation and got it working. Add the following meta tag into your global template
<meta name="csrf-token" content="{{ csrf_token() }}">
Add this JavaScript that sets defaults for all ajax request in jQuery. Preferably in a js file that is included across your app.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
This token can exist in the request header or the form. This populates it into the request header of every ajax request.
You have to insert a hidden input with the _token and later get that value as you do to get the other form fields in your ajax post.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
An another method,
On your view you can set an object with the _token
<script type="text/javascript">
var _globalObj = {{ json_encode(array('_token'=> csrf_token())) }}
</script>
and later on your ajax call you can get the _token from the object like this:
var token = _globalObj._token;
and include it on your ajax post.
Just do simple thing as i have shown in following code,
$.ajax({
type: 'POST',
url: 'your-post-route-url',
data: {
"_token": "{{ csrf_token() }}",
"form_data": $('#Form').serialize(),
},
success: function (data) {
console.log(data);
},
error: function (reject) {
console.log(reject);
}
});
I hope this one is the easiest way to solve this problem without any hidden field and it works for me in laravel 5.4 version :)
Hope it helps.
You can as well add the url thats giving you the error inside the VerifyCsrfToken.php file in the
protected $except = [
//
]
Let's say your route is post. You can just add in like this
protected $except = ['post',
//
];`...
Hope this helps others.
<html>
<head>
<title>Ajax Example</title>
<meta name="csrf-token" content="<?php echo csrf_token() ?>" />
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
data:'',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</br>
</body>
</html>
and VerifyCsrfToken.php file add this function
protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
return $request->session()->token() == $token;
}

Categories