Laravel - DELETE Ajax request - laravel

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

Related

Laravel 8 Method Not Allowed 405 Ajax CRUD

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

Why do I always get undefined value from other data?

I always get undefined values from other data for example: ID:123 the response for this would be the NetAmount: 1000.00 after sending it using AJAX GET REQUEST, so for other data it would just return an undefined value.
MY AJAX
function viewBill(AccountNum){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "GET",
url: "{{ route('view.billing') }}",
data: {AccountNum:AccountNum},
dataType: 'json',
async: true,
beforeSend: function() {$('#userBill').html('Getting Information...')},
success: function(res) {
console.log(res.NetAmount);
$('#checkBill').css('display','block');
$('#userBill').html('₱ '+res.NetAmount);
},
error: function(res) {console.log('Error');},
complete: function() {
}
});
}
My Controller
public function viewBilling(Request $request){
if($request->ajax()){
$viewBilling = Table1::addSelect(['PaymentStatus' => Table2::selectRaw('COUNT(*)')
->whereColumn('AccountNumber','Table1.AccountNumber')
->whereColumn('ServicePeriodEnd','Table1.ServicePeriodEnd')
->where('AccountNumber', $request->AccountNum)
])->where('AccountNumber', $request->AccountNum)
->orderBy('ServicePeriod','desc')
->first();
return Response()->json($viewBilling);
}
}
I tried using dd() and it turns out there are values for the account I tried from the one that returns the NetAmount and from the one that returns an undefined value.
Found the problem, because of the parameter of my viewBill() function, I don't know why would it give me undefined values from other data I did check using the network tools, it just that it wasn't able to send the AccountNumber to the Controller. So I tried removing the parameter. I have an input tag that already has the value of the Account Number so instead of using the above code, I did this
function viewBill(){
var AccountNum = $('#inputAccountNum1').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post({
url: "{{ route('view.billing') }}",
data: {AccountNum:AccountNum},
dataType: 'json',
beforeSend: function() {$('#userBill').html('Getting Information...')},
success: function(res) {
$('#checkBill').css('display','block');
$('#userBill').html('₱ '+res.NetAmount);
},
error: function(res) {console.log('Error');},
complete: function() {
}
});
}

CSRF token not working in a Laravel ajax call

I've checked the gizillion answers to this question and for some reason I can't get this to work.
I get the error:
401 (Unauthorized)
My route is an api route guarded.
My data:
let ajaxMainTemplate = {
'mainTemplate': mainTemplate,
'templateId': templateId,
'_token': accessToken,
}
My ajax call:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
data: {
_token: ajaxData._token,
ajaxData
},
success: function(response) {
console.log(response)
}
})
I've tried the above to test based on another response. I put the token outside of the ajaxData object. I get the same error. I've also attempted:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
headers: { 'X-CSRF-TOKEN': ajaxData._token },
data: ajaxData,
success: function(response) {
console.log(response)
}
})
Same.
I've also confirmed the token is there by adding a console.log Any ideas what I'm doing wrong with this?
My url was behind the api protected route so I had to do an ajax call to login into it via ajax.
The credentials are in a variable ajaxData.
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8000/api/login',
data: ajaxData,
success: function(response) {
shopifyToken = response.success.token;
getListProducts(shopifyToken);
}
});
With the shopify token generated from this login it worked.

How to insert data in the database using ajax in laravel?

I'm working on a simple web application in the laravel framework. I have blade, controller and model files and I want to insert the data into the database with the help of ajax. But, I'm not able to insert the data. Below is the code:
Thanks.
<script>
$(document).ready(function(){
$("#button").on("click", function(){
var name=$("#name").val();
var email=$("#email").val();
$.ajax({
url:'insert.php',
method:'POST',
data:{
name:name,
email:email,
},
success:function(data){
alert(data);
}
});
});
});
</script>
There are so many issue with your code:
url:'insert.php', // here you are not working in core php so url is not passed in this way
it will be like:
url:'{{ url("/insert") }}', // This 'insert' will be a route and that will be mapped to a controller function.
And if you are using:
method:'POST',
then you have to set the csrf token like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
or
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
Resolve the above issues and try again.
at least, you have to call in your script.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Because it is POST request, your csrf_token is required.

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

Resources