I have a simple button who throw this Ajax request :
function myfunction(param){
var date_debut = $('#datet_debut').val();
var date_fin = $('#date_fin').val();
$.ajax({
url: '{{ route('createDispo') }}',
type: 'POST',
dataType: "json",
data: {
date_debut: name,
date_fin: name,
},
success: function (data) {
alert('success');
},
error: function (e) {
console.log(e.responseText);
}
});
}
But I have this error :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message
The route is generated like that :
Route::post('/createDispo','DepotDispoController#createDispo')->name('createDispo');
Here is the controller to handle the request :
public function createDispo(Request $request){
$user = User::find($request->user_id);
$disponibilite = new Disponibilite();
$disponibilite->date_debut = $request->date_debut;
$disponibilite->date_fin = $request->date_fin;
$user->disponibilites()->save($disponibilite);
}
So, why my Ajax request doesn't work ?
Remember to check that your method in the routes correspond to the method your are submiting.
Also, when submiting POST request Via Ajax you have to set the csrf token:
In your HTML header
<meta name="csrf-token" content="{{ csrf_token() }}">
Before ajax call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Related
I have a form to create a card, this form is public, when a person fills out the form and wants to publish their card, they are asked to log in or if they are a new user to register.
I suppose that when the login is requested, the token that was immersed in the form expires and throws the 419 error.
How can I login and update the token to avoid error 419?
I am not an expert in Laravel so any suggestions would be appreciated.
reference diagram
here a part of the code that I have implemented
Login via AJAX
$(function () {
$('#login-form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var url = form.prop('action');
let data = form.serializeArray();
console.log(data);
$.ajax({
type: "post",
headers: {
Accept: "application/json",
},
url: url,
data: form.serializeArray(),
success: function(json) {
console.log('OK')
},
error: function(json) {
console.log('NOK')
alert(json);
},
});
});
});
Controller
public function __construct()
{
$this->middleware('create.card.newuser')->only('store');
$this->middleware('auth')->except(['create', 'store']);
}
Middleware "CreateCardIfNewUser"
public function handle(Request $request, Closure $next)
{
if (! Auth::user() )
{
return redirect()->route('digital_card.create')->with('openModalLogin', true)
->withInput($request->all());
}
return $next($request);
}
View 'layouts.app'
#if(session()->has('openModalLogin'))
<script>
$('#login-modal').modal({
show: true
});
</script>
#endif
Pass the csrf_token to the data:
…
data : {
_token: "{{ csrf_token() }}"
}
your error is due to the absence of csrf token. this solution is not only valid on this problem. each time you will have this problem of 419 then you must immediately think of the csrf token
data: {
_token: "{{ csrf_token() }}"
}
you must always add a csrf token to each submission otherwise you will always get this error
data: {
_token: "{{ csrf_token() }}"
},
I want to pass the unlock key to route using ajax but I am not allowed to do so. The code gives me method not allowed error.
I cant see the error in my code, whether it the route error or some other error
<script>
$(document).ready(function(){
$('.result-container').hide();
$('.unlock-btn').on('click', function(){
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})
});
});
</script>
So your route is a get but in ajax you are sending post request. Change it to post.
Route::post('/unlock', 'ThemeController#unlock')->name('unlock');
And also add a token in data otherwise you will get 419 error for missing CSRF.
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
"_token": "{{ csrf_token() }}",
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})
In my application i am using Ajax request but it is giving me jquery-3.3.1.js:9600 POST http://localhost:8000/get_types_ajax
gettin 419 (unknown status)
My javascript is:
$(document).ready(function() {
var ckbox = $("input[name='particulars']");
var chkId = '';
$("input[name='particulars']").on('change', function() {
if (ckbox.is(':checked')) {
values = [];
names = [];
$("input[name='particulars']:checked").each ( function() {
amount = $(this).val().split(",");
console.log("amount",amount);
values.push(amount[0]);
names.push(amount[1]);
});//checked
total_value = 0;
values.forEach(function(value) {
value = Number(value);
total_value = total_value + value;
document.getElementById('total').innerHTML = total_value;
});//foreach
}//if
else {
total_value = 0;
document.getElementById('total').innerHTML = total_value;
}
$.ajax({ url:"{{url('/get_types_ajax')}}",
type: 'POST',
data: {message:names},
success: function (data)
{
console.log(data);
}
});
});//onchange
});//ready
my web.php is :
Route::post('/get_types_ajax', 'DevkrutyaController#get_types');
The 419 error you are getting is due to the missing CSRF token in your ajax request. To pass a csrf token you can use ajax setup method of jquery
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
$.ajax({
url:"{{url('/get_types_ajax')}}",
type: 'POST',
data: {message:names},
success: function (data)
{
console.log(data);
}
});
});//onchange
});//ready
For more information https://laravel.com/docs/master/csrf#csrf-x-csrf-token
i see.You don't pass CSRF_TOKEN WITH Post Request
if your are using post method then u must pass CSRF_TOKEN with that other wise you can ignore(skip) some Url in VerifyCSRF token middleware
protected $except = [
'stripe/*',
];
other wise add this line in your js file it will automatically send
csrf token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
for more detail read this article
Laravel uses CSRF token to protect your application from cross-site request forgery (CSRF) attacks. You will need to pass the CSRF token in your ajax.
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>
This is my first attempt to use ajax to Post instead of Get. I get a 200 response as if it were working but the function in the controller is never being run.
I used this same concept in my ajax Get requests and they work fine but the Post is not working as expected and sortable('serialize') creates a Post variable so I need to use Post.
The alert in the success: function always runs as if it were successful but the controller function is never hit (I have it making a simple database change just to verify if it is running).
Ajax:
$(function() {
$('[id^="sortable_"]').sortable(
{
connectWith: '.sortable-line-item-list-5',
update : function (event, ui)
{
var items = $(this).sortable('serialize');
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
},
success: function()
{
alert('looks like it is working...');
},
});
}
});
$( '[id^="sortable_"]' ).disableSelection();
});
Route:
Route::post('api/sort_order_item', ['as' => 'api/sort_order_item', 'uses' =>'ApiController#SortOrderItem']);
Controller:
public function SortOrderItem()
{
$this_item = \pmms\Checklist_template_line_item::findOrFail(20);
$this_item->list_position = 1;
$this_item->save();
}
I think your problem is csrf_token,
Put this line in your blade page head section:
<meta name="csrf-token" content="{{ csrf_token() }}" />
then, update your ajax code like this :
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
success: function()
{
alert('looks like it is working...');
},
});
Let me know if it helps you
I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection