Laravel 8 Method Not Allowed 405 Ajax CRUD - laravel

I fixed my csrf
I fixed my route , route clear too
but still error show up .
I'm doing ajax form in modal :
My Route
Route::post('increp/store',[\App\Http\Controllers\IncrepController::class,'store'])->name('increp.store');
My ajax
// Create article Ajax request.
$('#submit_increp').click(function(e) {
e.preventDefault();
var data = $("#main-form").serialize();
$.ajax({
url: "{{ route('increp.store') }}",
type: 'POST',
data: data,
dataType: 'json',
beforeSend:function(){
$(document).find('span.error-text').text('');
},
success: function(result) {
if(result.errors) {
console.log(result.errors);
$('.alert-danger').html('');
$.each(result.errors, function(key, val) {
$('span.'+key+'_error').text(val[0]);
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
}
}
});
});
I doing this for days, i dont have idea how to fix this errors .
Network tab
Console tab

Related

Ajax in Django : url not found

I am coding a small Django project where an user can select an object and save it in a database. I am trying to implement an Ajax call on a button to delete this object if necessary.
I am doing it step by step, debugging with the console.
my urls:
app_name = 'register'
urlpatterns = [
path('<int:user_id>/', views.account, name='account'),
path('/delete/', views.delete, name='delete'),
]
my view.py:
def delete(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
print(product)
data['success'] = True
return JsonResponse(data)
my ajax.js:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
console.log('ok till this point')
$.ajax({
url: '{% url "register/delete" %}',
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
My view isn't doing much for now but I haven't any knowledge about Ajax and I am doing it one step at a time.
This is the error I get in the console:
jquery.min.js:2 POST http://127.0.0.1:8000/register/6/%7B%%20url%20%22register/delete%22%20%%7D 404 (Not Found)
As far as I understand, Ajax can't find my url: '{% url "register/delete" %}'.
I have tried '{% url "register:delete" %}' with no luck either.
I found an answer after some tweaking, I defined my url before the Ajax call and then pass it in it:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
var url = '/register/delete/'
console.log( url)
$.ajax({
url: url,
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
Also you can add just the string of url to "url" parameter without characters {% url %}. Maybe you copied the code from pattern Django and added it to JS-file. So it does not work.

POST http://127.0.0.1:8000/unlock 405 (Method Not Allowed)

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])}}";
}
}
})

Laravel - ajax creates double input

I have made this ajax request to show the validation errors and prevent the page to reload
$(document).on('mousedown', ':submit', function() {
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
All is fine with this code! The problem is that after successfull submit i have 2 inputs in DB...how can i prevent this?
Are you sure the form isn't actually submitting and saving the values once by post and once by ajax? Usually if you're capturing a submit event you listen for the forms submit even not the mousedown event of the submit button e.g.
$('form').on('submit', function(e) {
// Stop the forms default submit action
e.preventDefault();
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
Also the e.preventDefault() will prevent the form from submitting itself along with your ajax action. Also you'd best off selecting your form by an ID or class name.

Laravel - DELETE Ajax request

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

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Resources