When I use a POST method with the following ajax request, it throws a "Method not allowed" error. If I use the form POST without using ajax, it goes to the proper method.
In Router.php:
$this->post('TestPost','DashboardController#TestPostMethod');
In View, the ajax request is:
$.ajax(
{
type: "POST",
url: 'TestPost',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
alert('hid post');
SetHotandWorstData(data,'hotquantity');
},
error: function (msg) {
alert('error');
alert(msg.responseText);
}
});
In Controller:
function TestPostMethod(Request $request)
{
$hotworstsalesdata = DB::table('100_INVOICEDETAIL')
->select( '100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME',
DB::raw('SUM("100_INVOICEDETAIL"."QTY") as
salesqty'), DB::raw('SUM("100_INVOICEDETAIL"."AMT") as salesamt'))
->groupBy('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME')
->orderBy('salesqty')
->take(10)
->get();
return Datatables::of($hotworstsalesdata)->make(true);
}
you should pass "_token" in POST data. Laravel use token for cross-site request forgery (CSRF) attacks. use following code in your AJAX request
data: { _token: "{{ csrf_token() }}" }
Updated answer:
I have re-create same scenario on my system with laravel 5.4 and it's working for me.
my route (web.php) code is:
Route::post('/test_post', 'DashboardController#getData');
Javascript code is:
<script type="text/javascript">
$.ajax({
type: "POST",
url: '{{ url('/') }}/test_post',
data: { _token: "{{ csrf_token() }}" },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
console.log(data);
},
error: function (msg) {
console.log(msg.responseText);
}
});
</script>
DashboardController file is:
public function getData(Request $request) {
print_r($request);
}
Recently I got error with DELETE method ! I fixed by setting csrf token in html header and get in ajax . Hope this can solve your problem ..
<html>
<header>
<meta name="csrf-token" content="{{ csrf_token() }}" />
In ajax,
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Related
I'm working on Laravel and trying to send a variable to a controller using AJAX, but the request is changing to GET!
AJAX
function fetchTasks(email) {
$.ajax({
method: 'POST',
dataType: 'json',
url: '/teamwork',
data: {_method: 'POST', email : email},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
Routes.php
Route::any('/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
When i change the route method to post, it shows a 405(Method Not Allowed)
When i dd($request) in my controller, this is what i get
image
So, why my Ajax request doesn't work ?
EDITED:
I've modified my code to the following
function fetchTasks(email) {
console.log(email);
var token = "{{ csrf_token() }}";
$.ajax({
method: "POST",
url: "teamwork",
data: {
_token:token,
'email': email
},
contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
},
complete: function () {
window.location.href = '{{route("testTRoute")}}';
}
});
}
It's still sending an empty GET request. Output from console is the following:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Based on ajax documentation you should use type param instead method.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Have u tried this?
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:'teamwork' ,
type:'post',
data: { email : email},
method: 'POST',
dataType: 'json',
success:function(result){console.log(result);}
});
Route
Route::match(array('GET','POST'),'/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
If you want to send 'email' as a route parameter but don't want to show it in browser's address bar, you can do it as below.
Sending data through a form
At you blade.php
<form action="{{route('testPRoute')}}" method="POST">
#csrf
<!--
Set your email name or variable in input's value attribute. Like
<input type="text" name="email" value="email">
or
<input type="text" name="email" value="{{$email}}">
or -->
<input type="hidden" name="email" value="email">
<button type="submit">Go to Route</button>
</form>
At your Web.php
Route::post('/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
At your Controller
public function teamwork(Request $request)
{
$email = $request->email;
return $email;
}
After a long time of debugging, i have found that my problem was with the routing. I had two routes, GET and POST with the same name. That's why it was always sending a GET request.
im sending a form data via ajax to the server using laravel 5.6
when sending the data to the server, i have specified the method of ajax to POST and the routing method in web.php to post too, the problem is, ajax sendS the form data with GET method not POST. what should i change???
ajax code
var form = $('#personPersonalInfoForm')[0];
var formData = new FormData(form);
$.ajax({
url:"/addNewPerson",
Type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data)
{
alert(data);
}
});
web.php code
Route::post('/addNewPerson', 'adminController#addNewPerson');
Here is an example of working code using the FormData.
Using the "method" configuration instead of "type".
var form = document.getElementById("ajaxForm");
var formData = new FormData(form);
var url = form.action;
$.ajax({
method : 'POST',
url : url,
data : formData,
contentType: false,
processData: false
}).done(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
Dont forget to add the CSRF token in the form.
<form method="POST" action="/addNewPerson" id="ajaxForm">
#csrf
...
</form>
Or configure the ajax method from the start with it.
in the < head> add
<meta name="csrf-token" content="{{ csrf_token() }}">
and in the JavaScript add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
web.php
Route::post('/addNewPerson', 'adminController#addNewPerson')->name(admin.add_new_person);
in your adminController :
public function addNewPerson(Request $request){
// you can check request parameters
//return response()->json($request->all());
// add new person code here ...
return response()->json(array('status'=>'success','message'=>'person added'));
}
your ajax code should be :
$.ajax({
url:"/addNewPerson",
type: "POST",
data:$('#personPersonalInfoForm').serialize(),
dataType:'json',
contentType: 'application/json',
success: function(data)
{
alert(data);
},
error:function(){
alert('ERROR');
}
});
I am requesting POST :
Route :
Route::post('/register','CommonController#postRegister')->name('register');
CSRF Meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
$("#submitSalonForm").click(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/register",
type: "post",
data: new FormData($('form')[1]),
cache: false,
contentType: false,
processData: false,
success:function(response) {
return alert('Form 2 submitted');
}
});
});
And the exception :
The exception comes sometimes and sometimes the code runs smoothly, I have no idea what am i missing here.
Change ajax method from post to get
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Ajx call:
let formData = $('form').serializeArray();
$.ajax({
url: "/register",
type: "POST",
data: {formData, "_token": $('#token').val()},
cache: false,
datatype: 'JSON',
processData: false,
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
Your route is get
Route::get('/register','CommonController#showRegister')->name('register');
Ajax call is making a post request, laravel sqwaks with a http exception.
EDIT:
Laravel 419 post error is usually related with api.php and token authorization
So try to include the token on ajax body instead like above.
In addition to putting the crsf-token value in the header meta tag you need to pass it through in your AJAX requests like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
No need to setup ajax separately. Laravel automatically generates a CSRF "token" for each active user session managed by the application. Get the token with this:
var token = "{{ csrf_token() }}";
Pass the token in data
var token = "{{ csrf_token() }}";
var formData = new FormData($('form')[1])
$.ajax({
url : '/register',
data : {_token:token,formData:formData},
type: 'post',
...
})
Well, I know I am too late, but I did face the exact issue you face.
I was 100% sure that the token has been sent with the request, but the issue is still.
So, after too many searches I finally got it fixed by following these steps:
php artisan config:clear
php artisan view:clear
php artisan route:clear
php artisan cache:clear
php artisan clear-compiled
I am doing just basic subscribe form, trying to use Ajax post request.
Since I am new to Ajax I googled some about this issue but no success, even though it is an easy fix probably.
The issue is, that when I submit form, it will throw me error:
MethodNotAllowedHttpException No message
View.blade:
//Ajax
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#subscribeform").submit(function (e) {
e.preventDefault();
var emailval = $('#subscriber').val();
console.log(emailval);
if(emailval !== "") {
$.ajax({
cache: false,
url: '/subscribing',
type: 'POST',
dataType: 'json',
data: {
email:emailval
},
success: function (data) {
console.log(data);
}
});
}
});
</script>
//Form
<form id="subscribeform" method="post">
<input type="text" name="subscriber" id="subscriber" placeholder=" email#example.com">
<input type="submit" value="Submit">
</form>
Route
Route::post('/subscribing', 'SubsController#store');
Controller
class SubsController extends Controller
{
public function store(Request $request)
{
$newsubscriber = new Subscriber;
$newsubscriber->email = $request->input('email');
$newsubscriber->save();
}
}
Namespacing is good I am sure, so what could be an issue really?
Change "type" to "method".
You are also forgetting the CSRF token in your AJAX call. Add it as a parameter :
_token : {{ csrf_token() }}
Blade will insert it into your js.
According to above answers i think it is because of csrf_token, to solve your problem try like this,
You need to use ajaxSetup as recommended in the docs like below,
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
and also add this on your template,
<meta name="csrf-token" content="{{ csrf_token() }}">
Or alternatively just add this to your form,
<meta name="csrf-token" content="{{ csrf_token() }}" />
For more details read doc.
Use in your SubsController.php
use App\Subscriber;
Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#subscribeform").submit(function (e) {
e.preventDefault();
var emailval = $('#subscriber').val();
console.log(emailval);
if(emailval !== "") {
$.ajax({
cache: false,
url: '/subscribing',
type: 'POST',
dataType: 'json',
data: {
_token: '{!! csrf_token() !!}',
email:emailval
},
success: function (data) {
console.log(data);
}
});
}
});
Model `Subscriber.php'
class Subscriber extends Model
{
protected $fillable = ['email'];
protected $table = 'subscriber';
}
And add following code to your header:
<meta name="csrf-token" content="{{ csrf_token() }}">
According to Jquery docs, the key for request method in ajax settings is "method", not "type", which means Your request is GET by default. Therefore Method is not allowed, as stated in exception.
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.
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
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);
},
});
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.
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'));
}
},
});
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.
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
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.
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
}
});
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.
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>
...
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: "test#test.com"},
success:function(response){
// Log response
console.log(response);
}
});
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);
},
});
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
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));
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.
just serialize the form data and get your problem solved.
data: $('#form_id').serialize(),
This error also happens if u forgot to include this, in your ajax submission request ( POST ),
contentType: false,
processData: false,
Got this error even though I had already been sending csrf token. Turned out there was no more space left on server.
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() ?>'
}
});
A simple way to fixe a 419 unknown status on your console is to put this script inside in your FORM. {{ csrf_field() }}
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}`);