This is my form id:
<form id="signupForm" method="POST" class="pt-3" action="{{ route('login') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
#csrf
And this is the ajax I use:
function loginUser()
{
// console.log('here');
// e.preventDefault();
var formData = new FormData(jQuery('#signupForm')[0]);
$.ajax({
url:"home",
type:"POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:formData,
contentType: false,
processData: false,
success:function(data)
{
// console.log(data.data.role);
// return;
// window.location = "http://localhost/dashboard_new/public/home";
if(data.code==200)
{
window.location = "http://localhost/dashboard_new/public/home";
}
if(data.code==400)
{
$('#form_submit_error').modal('show');
setTimeout(function() {$('#form_submit_error').modal('hide');}, 2000);
}
}, error: function (xhr, status, error)
{
// console.log(xhr.responseJSON.errors);
$.each(xhr.responseJSON.errors,function(key,item)
{
if(data.code==400)
{
$('#form_submit_error').modal('show');
setTimeout(function() {$('#form_submit_error').modal('hide');}, 2000);
}
})
}
});
}
This is the route:
Route::view('/','welcome');
Route::get('welcome', 'HomeController#loginUser');
This is the screenshot of submitted data for login, the message occurs "submitted", but it doesn't read my database and even doesn't respond..even in inspect element it says that
POST http://localhost:8000/home 405 (Method Not Allowed)
,
Actually Laravel says that there is not such a method that you called. Its simply because of the get method which you defined in Laravel router. Define a route like this:
Route::post('login', 'HomeController#loginUser');
and in your Ajax request you should change url property to login:
$.ajax({
url:"login", // <= here
type:"POST",
...
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
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;
}
I am trying to delete data from database via ajax.
HTML:
#foreach($a as $lis)
//some code
Delete
//click action perform on this link
#endforeach
My ajax code:
$('body').on('click', '.delteadd', function (e) {
e.preventDefault();
//alert('am i here');
if (confirm('Are you sure you want to Delete Ad ?')) {
var id = $(this).attr('id');
$.ajax({
method: "POST",
url: "{{url()}}/delteadd",
}).done(function( msg ) {
if(msg.error == 0){
//$('.sucess-status-update').html(msg.message);
alert(msg.message);
}else{
alert(msg.message);
//$('.error-favourite-message').html(msg.message);
}
});
} else {
return false;
}
});
This is my query to fetch data from database...
$a = Test::with('hitsCount')->where('userid', $id)->get()->toArray();
But when i click on Delete link data not deleted and show csrf_token mismatch...
The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
You have to add data in your ajax request. I hope so it will be work.
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
I just added headers: in ajax call:
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
in view:
<div id = 'msg'>
This message will be replaced using Ajax. Click the button to replace the message.
</div>
{!! Form::submit('Change', array('id' => 'ajax')) !!}
ajax function:
<script>
$(document).ready(function() {
$(document).on('click', '#ajax', function () {
$.ajax({
type:'POST',
url:'/ajax',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success:function(data){
$("#msg").html(data.msg);
}
});
});
});
</script>
in controller:
public function call(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
in routes.php
Route::post('ajax', 'AjaxController#call');
Laravel 8^
Route::post('ajax', [AjaxController::class, 'call']);
I think is better put the token in the form, and get this token by id
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
And the JQUery :
var data = {
"_token": $('#token').val()
};
this way, your JS don't need to be in your blade files.
If you are using template files, than you can put your meta tag in the head section (or whatever you name it) which contain your meta tags.
#section('head')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#endsection
Next thing, you need to put the headers attribute to your ajax(in my example, I am using datatable with server-side processing:
"headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
Here is the full datatable ajax example:
$('#datatable_users').DataTable({
"responsive": true,
"serverSide": true,
"processing": true,
"paging": true,
"searching": { "regex": true },
"lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
"pageLength": 10,
"ajax": {
"type": "POST",
"headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
"url": "/getUsers",
"dataType": "json",
"contentType": 'application/json; charset=utf-8',
"data": function (data) {
console.log(data);
},
"complete": function(response) {
console.log(response);
}
}
});
After doing this, you should get 200 status for your ajax request.
Know that there is an X-XSRF-TOKEN cookie that is set for convenience. Framework like Angular and others set it by default. Check this in the doc https://laravel.com/docs/5.7/csrf#csrf-x-xsrf-token
You may like to use it.
The best way is to use the meta, case the cookies are deactivated.
var xsrfToken = decodeURIComponent(readCookie('XSRF-TOKEN'));
if (xsrfToken) {
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': xsrfToken
}
});
} else console.error('....');
Here the recommended meta way (you can put the field any way, but meta is quiet nice):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Note the use of decodeURIComponent(), it's decode from uri format which is used to store the cookie. [otherwise you will get an invalid payload exception in laravel].
Here the section about the csrf cookie in the doc to check :
https://laravel.com/docs/5.7/csrf#csrf-x-csrf-token
Also here how laravel (bootstrap.js) is setting it for axios by default:
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
you can go check resources/js/bootstrap.js.
And here read cookie function:
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
Add an id to the meta element that holds the token
<meta name="csrf-token" id="csrf-token" content="{{ csrf_token() }}">
And then you can get it in your Javascript
$.ajax({
url : "your_url",
method:"post",
data : {
"_token": $('#csrf-token')[0].content //pass the CSRF_TOKEN()
},
...
});
EDIT: Easier way without changing the meta line.
data : {
_token: "{{ csrf_token() }}"
}
Or
data : {
_token: #json(csrf_token()),
}
Thanks to #martin-hartmann
you have to include this line in master file
<meta name="csrf-token" content="{{ csrf_token() }}" />
and while calling ajax you have to implement csrf token ,
$.ajax({
url:url,
data:{
_token:"{{ csrf_token() }}"
},
success:function(result){
//success message after the controller is done..
}
})
if you are using jQuery to send AJAX Posts, add this code to all views:
$( document ).on( 'ajaxSend', addLaravelCSRF );
function addLaravelCSRF( event, jqxhr, settings ) {
jqxhr.setRequestHeader( 'X-XSRF-TOKEN', getCookie( 'XSRF-TOKEN' ) );
}
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
Laravel adds a XSRF cookie to all requests, and we automatically append it to all AJAX requests just before submit.
You may replace getCookie function if there is another function or jQuery plugin to do the same thing.
who ever is getting problem with the accepted answer #Deepak saini, try to remove
cache:false,
processData:false,
contentType:false,
for ajax call.
use
dataType:"json",
In case your session expires, you can use this, to login again
$(document).ajaxComplete(function(e, xhr, opt){
if(xhr.status===419){
if(xhr.responseJSON && xhr.responseJSON.message=='CSRF token mismatch.') window.location.reload();
}
});
You should include a hidden CSRF (cross site request forgery) token field in the form so that the CSRF protection middleware can validate the request.
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.
So when doing ajax requests, you'll need to pass the csrf token via data parameter.
Here's the sample code.
var request = $.ajax({
url : "http://localhost/some/action",
method:"post",
data : {"_token":"{{ csrf_token() }}"} //pass the CSRF_TOKEN()
});
xxxxxxxOld answer deletedxxxxxxx
CLARIFICATION/UPDATE
The csrf token in the meta header is used for session management
Laravel automatically generates a CSRF "token" for each active user session managed by the application.
It is the same value as that contained in:
#csrf directive inside a form or anywhere else in a Blade template (this generates the _token hidden input field).
csrf_token() global helper function used anywhere in a controller or Blade template.
Important
For sessions that are not yet authenticated, the CSRF token is regenerated/different for every served page - i.e. new session data is generated for every loaded page.
For a session that is authenticated, the CSRF token is the same for all pages - i.e. session data is maintained across all loaded pages.
Conclusion
Include the CSRF token in Ajax request in the following way:
from the meta header or the generated hidden _token input field - useful when sending Ajax POST request with a form:
<script>
$(document).ready(function() {
let token = $('meta[name="csrf_token"]').attr('content');
// let token = $('form').find('input[name="_token"]').val(); // this will also work
let myData = $('form').find('input[name="my_data"]').val();
$('form').submit(function() {
$.ajax({
type:'POST',
url:'/ajax',
data: {_token: token, my_data: myData}
// other ajax settings
});
return false;
});
});
</script>
Call csrf_token() in a hidden element in Blade template and get the token in js - useful when sending Ajax POST request without a form:
Blade:
<span id='csrf' style='display:none'>{{ csrf_token() }}<span>
JavaScript:
<script>
$(document).ready(function() {
let token = $('#csrf').html();
$.ajax({
type:'POST',
url:'/ajax',
data: {_token: token, my_data: 'john'}
// other ajax settings
});
});
</script>
I just use #csrf inside the form and its working fine
I always encounter this error recently. Make sure to use a more specific selector when referring to a value. for example instead of $('#firstname') use $('form').find('#firstname');
Laravel 5.8
use the csrf in the ajax url(separate js file)
$.ajax({
url: "/addCart" + "?_token=" + productCSRF,
type: "POST",
..
})
guys in new laravel you just need to do this anywhere. in JS or blade file and you will have csrf token.
var csrf = document.querySelector('meta[name="csrf-token"]').content;
it is vanilla JS. For Ajax you need to do this.
var csrf = document.querySelector('meta[name="csrf-token"]').content;
$.ajax({
url: 'my-own-url',
type: "POST",
data: { 'value': value, '_token': csrf },
success: function (response) {
console.log(response);
}
});
If you are work on laravel 7.0 project and facing this error
Adding a token as part of the parameter to be sent to the controller would solve the problem just like the answers given above. This is as a result of Laravel protecting your site against cross-site attack. which requires you to generate a unique token on every form submission.
"_token": "{{ csrf_token() }}"
You can now have;
const postFormData = {
'name' : $('input[name=name]').val(),
"_token": "{{ csrf_token() }}"
};
$.ajax({
url: 'pooling'
, type: 'post'
, data: postFormData
, dataType: 'json'
, success: function(response) { consolel.log(response) }
});
Simply putting csrfmiddlewaretoken: '{{ csrf_token }}' inside data works well!!
$.ajax({
url : "url where you want to send data"
type : "POST", // http method
data : {
name:"...",
csrfmiddlewaretoken: '{{ csrf_token }}' , #this works for me
},
// handle a successful response
success : function(data){
alert('......');
},
error : function() {
..............
}
});
There also could be a case when you define your $middlewareGroups
You should use the following format:
protected $middlewareGroups = [
'web' => [],
'api' => [
'web',
'throttle:500,1'
],
'basic' => [
'auth:basic',
]
];
If you're upgrading laravel from 5 to 8, and face this error, add following to app/Http/Middleware/VerifyCsrfToken.php:
public static function serialized()
{
return true;
}
In script tag in your blade file, do like this to generate a valid form token and get it in jQuery
<script>
$(document).ready(function() {
$("#my-upload-button").click(function() {
var token = "{{ csrf_token() }}";//here getting token from blade
$.post('my-url', {
_token: token,
datra: ...
},
function(data) {
alert(data);
});
});
});
I this problem was resolved for me just by removing processData: false
$.ajax({
url: '{{ route('login') }}' ,
method: 'POST',
data: {
_token : {{ csrf_token() }},
data : other_data,
},
cache: false,
//processData: false, // remove this
...
success: function(res){
...
}
});
In your main page (someViewsName.blade.php), declare a global variable
<script>
var token = "{{ csrf_token() }}";
</script>
<script src="/path/to/your_file.js"></script>
Then, in your_file.js
$.ajax({
type: "post",
url: "http://your.url/end/point",
data: {
_token:token,
data:your_data,
},
dataType: "json",
success: function (response) {
// code some stuff
}
});
Lol, I had the same issue tried each and every solution but after that checked env again and there was one flag true which causes the issue,
SESSION_SECURE_COOKIE=true
remove this line it will fix the issue.
I actually had this error and could not find a solution. I actually ended up not doing an ajax request. I don't know if this issue was due to this being sub domain on my server or what. Here's my jquery.
$('#deleteMeal').click(function(event) {
var theId = $(event.currentTarget).attr("data-mealId");
$(function() {
$( "#filler" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Are you sure you want to delete this Meal? Doing so will also delete this meal from other users Saved Meals.": function() {
$('#deleteMealLink').click();
// jQuery.ajax({
// url : 'http://www.mealog.com/mealtrist/meals/delete/' + theId,
// type : 'POST',
// success : function( response ) {
// $("#container").replaceWith("<h1 style='color:red'>Your Meal Has Been Deleted</h1>");
// }
// });
// similar behavior as clicking on a link
window.location.href = 'http://www.mealog.com/mealtrist/meals/delete/' + theId;
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
So I actually set up an anchor to go to my API rather than doing a post request, which is what I figure most applications do.
<p><a href="http://<?php echo $domain; ?>/mealtrist/meals/delete/{{ $meal->id }}" id="deleteMealLink" data-mealId="{{$meal->id}}" ></a></p>