I have the following route defined in my web.php
Route::delete('/contributions/contribution/destroy', 'ContributionController#destroy');
In my blade file I have a button that when clicked displays a sweetalert to confirm deletion. This works correctly, but when the user presses the delete button instead of it going to the URL defined in Ajax it goes to an incorrect URL and logs the following error:
jquery.min.js:4 DELETE http://localhost/contributions/batches/batch/edit 404 (Not Found)
Here is button code
<td class="text-center"><button type="button" class="btn btn-danger btn-sm btn-icon btn-destroy"
data-batch-id="{{ $batch->id }}"
data-id="{{ $contribution->id }}"
data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"
><i class="fa fa-times"></i></button>
</td>
Here is my script
<script>
$(document).on('click', '.btn-destroy', function (e) {
e.preventDefault();
var batchId = $(this).data('batch-id');
var id = $(this).data('id');
var amount = $(this).data('amount');
var contributor = $(this).data('contributor');
swal({
title: "Delete?",
text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
type: "error",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: "Delete",
closeOnConfirm: false
},
function() {
$.ajax({
url: "{{ url('/contributions/contribution/destroy') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: "DELETE",
data: {batch:batchId, contribution:id},
success: function (data) {
console.log(data);
}
});
});
});
oddly enough, refreshing the page after the error returns my session flash message from my controller's destroy function
*Note: I did add the DELETE verb to IIS, before this I was receiving:
405 (METHOD NOT ALLOWED)
Any ideas?
After two days of reading and wrenching I have a working solution:
route:
Route::delete('/contributions/contribution/destroy', 'ContributionController#destroy');
link html:
<a href="#" class="btn btn-danger btn-sm btn-icon btn-destroy"
data-id="{{ $contribution->id }}"
data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"><i class="fa fa-times"></i></a>
jquery/ajax:
<script>
$(document).on('click', '.btn-destroy', function (e) {
e.preventDefault();
var contributionId = $(this).data('id');
var amount = $(this).data('amount');
var contributor = $(this).data('contributor');
swal({
title: "Delete?",
text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
type: "error",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: "Delete",
closeOnConfirm: false
},
function() {
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
method: "DELETE",
url: "{{ url('/contributions/contribution/destroy') }}",
data: {contributionId:contributionId},
success: function (msg) {
if ( msg.status === 'success' ) {
swal("Deleted", msg.msg, "success");
setInterval(function() {
window.location.reload();
}, 3900);
}
},
error: function(msg) {
swal("Error!", "Something went wrong.", "error");
console.log(msg.status);
}
});
});
});
</script>
controller:
public function destroy(Request $request)
{
if ( $request->ajax() ) {
Contribution::find($request->contributionId)->delete();
return response(['msg' => 'Entry deleted', 'status' => 'success']);
}
return response(['msg' => 'Failed deleting the entry', 'status' => 'failed']);
}
Works perfectly!
Try this style of ajax
$.ajax({
url: "{{ url('/contributions/contribution/destroy') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
'data':{
'_method':'delete',
'_token':'{{ csrf_token() }}',
},
'method':'post'
});
in my case I removed the error by running simple classic:
php artisan route:clear
or you can launch that remotely. Create a route and a Controller and call it via browser link:
Route::get('/b/{x}', 'for_stuff\BController#kukuku');
and put into the controller's function:
Artisan::call('route:clear');
say:
https://mysite/b/r
Related
I tried to solve this problem:
The GET method is not supported for this route. Supported methods:
POST.
But I can not find right way and error on Laravel 8.
Here is blade:
<a href="{{ route('operDel',$data->id) }}" class="btn btn-danger btn-sm"
data-tr="tr_{{$data->id}}"
data-id="{{$data->id}}"
data-toggle="confirmation"
data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn-sm btn-danger"
data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left"
data-btn-cancel-class="btn btn-sm btn-default"
data-title="Are you sure you want to delete ?"
data-placement="left" data-singleton="true">Delete</a>
And JavaScript in this blade
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
Here is Route
Route::delete('operDel/{id}', '\App\Http\Controllers\OperationController#destroy')->name('operDel')->middleware('auth');
And this is Controller
public function destroy($id)
{
Kvit::where('id', $$id)->delete();
return response()->json([
'success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id
]);
}
What I missed?
You need to pass method to the server.
$.ajax({
url: "operDel/"+id,
type: 'get',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function(data){
//do stuff
},
error: function(data){
//do stuff
}
);
Solved by this code
Blade
<button class="btn btn-icon btn-flat-danger deleteRecord"
data-id="{{$data->id}}">
<i class="fas fa-trash"></i>
</button>
JavaScript
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
if(confirm('Do you want to delete?')){
$.ajax(
{
url: "operDel/"+id,
type: 'post',
cache: false,
data: {
"id": id,
"method": 'post',
"_token": token,
},
dataType: "json",
success: function(response) {
if(response.status == "success"){
window.location.href='/operations';
}else if(response.status == "error"){
{toastr['error'](
'Please check datas..',
'You can not delete this!',
{
closeButton: true, tapToDismiss: true, progressBar: true,
}
);
}
}
},
});
}
});
I wrote a script that should delete a specific entry. The problem is that when you click on the delete button, the record does not disappear, you have to reload the page to make it disappear. And only the first record in the database is deleted, for example, if I click delete the record with id = 2, then the record with id = 1 will be deleted. And I just can not understand why this is happening.
This is my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('data-id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deletePost',['id' => $post->id])}}",
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
}
});
return false;
});
});
</script>
Method
public function delete($id) {
$post = Profile::find($id);
$post->delete();
return response()->json([
'message' => 'deleted...'
]);
}
Route
Route::delete('/id{id}/delete', 'ProfileController#delete')->name('deletePost');
And html
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
</form>
change
var id = $(this).data('data-id');
to
var id = $(this).data('id');
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
// call your data get function here for disappear record after delele
}
});
return false;
});
});
</script>
Change the route to :
Route::delete('delete/{id}', 'ProfileController#delete')->name('deletePost');
Delete Method are just fine.
There are no need form for delete button
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
You wrongly access attribute data-id of button delete.
It should be
var id = $(this).data('id');
Or
var id = $(this).attr('data-id');
I have some code to request datatable via jquery ajax that returns:
403 forbidden
in a production environment, it's working properly in my local environment.
When I open url directly in browser it shows JSON array.
this is my ajax request:
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var state = true;
var otable = $('#example').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('get.data') }}",
columns: [
{ data: 'CountryCode', name: 'CountryCode' },
{ data: 'CountryName', name: 'CountryName' },
{ data: 'FgActive', name: 'FgActive' },
{ data: 'action', name: 'action' }
]
});
my route
Route::get('get-data-my-datatables', [
'as'=>'get.data',
'uses'=>'CountryController#getData'
]);
Below is function in controller
public function getData()
{
$country = Country::all();
return datatables()
->of($country)
->addColumn('action', function ($country) {
return
'<button type="button" name="'.$country->CountryCode.'" class="btn btn-primary btn-sm fa fa-pencil" id="btnEdit" data-toggle="modal"></button>
<button type="button" name="'.$country->CountryCode.'" class="btn btn-danger btn-sm fa fa-trash" id="btnDel" data-toggle="modal"></button>'
;
})
->make(true);
}
Thank you for your attention.
Update
As requested, this is my network tab:
I have form to POST data to Controller and update database
The form in my orders.blade.php
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<select name="selectdb" required>
<option value="" disabled selected>Select Delivery Boy</option>
#foreach($delvery_boys as $delvery_boy)
<option name="selectdb" data-oid="{{$order->id}}" value="{{$delvery_boy->id}}">{{$delvery_boy->name}}</option>
#endforeach
</select>
<button type="submit" class="assigndb-btn btn-floating waves-effect waves-light">
<i class="material-icons">send</i>
</button>
</form>
I am doing an ajax POST request of form data to controller in my orders.blade.php
$(document).one("click", ".assigndb-btn", function () {
$('form').submit(function(event) {
event.preventDefault();
var order_id = $(this).find(":selected").data('oid');
var delivery_boy_id = $(this).find(":selected").val();
var delivery_boy_name = $(this).find(":selected").text();
$.ajax({
url: '{{ url('/manager/assign_orders') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And in my OrdersController.php i have the logic to updated the posted data
public function assignDeliveryBoy(Request $request)
{
$assign_delivery_boy = Order::where('id', $request->order_id)->update(['delivery_boy_id' => $request->delivery_boy_id]);
$data = [
'success' => true,
'message' => 'Order has been asigned'
];
return response()->json($data);
}
My Route is
Route::group(['prefix' => 'manager', 'middleware' => ['auth','roles'], 'roles' => 'manager'], function() {
Route::post('/assign_orders', 'OrdersController#assignDeliveryBoy')->name('assignOrder');
});
When i submit the form it suppose to hit the assign_order route and update the database
But in my console i am getting the html code of the page from where i submit the form basically it is executing GET instead of POST
As i checked in browser network whent the response is
Request URL:http://localhost:8000/manager/orders //but i am posting to http://localhost:8000/manager/assign_orders
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
i really don't understand what is wrong
thank you
Try this code.
$.ajax({
url: "{{ url('/manager/assign_orders') }}",
type: 'POST',
data:{
"order_id":order_id,
"delivery_boy_id":delivery_boy_id,
'_token':'{{ csrf_token() }}'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
Let me know if it works.
Try this:
$.ajax({
url: '{{ route('assignOrder') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
$.ajax({
url: '{{ route("assignOrder") }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id,'_token':'{{ csrf_token() }}'},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
I'm trying to delete a row in db with Jquery / Ajax.
I have followed this thread but I can't make it working.
Here is my view:
#foreach($tournaments as $tournament)
<tr id="line" data-id="{{$tournament->id}}">
<td>
{{ $tournament->id }}
</td>
<td>{{ $tournament->owner->name}}</td>
<td class="text-center">
{!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteTourament', 'action' => ['TournamentController#destroy', $tournament->id]]) !!}
{!! Form::button( '<i class="glyphicon glyphicon-remove"></i>', ['class' => 'btn text-warning-600 btn-flat btnDeleteTournament', 'data-id' => $tournament->id ] ) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
<script>
$(function () {
$('#.tnDeleteTournament').on('click', function (e) {
var inputData = $('#formDeleteTourament').serialize();
var dataId = $('.btnDeleteTournament').attr('data-id');
console.log(inputData); // displays: _method=DELETE&_token=tGFhaAr5fVhDXEYL3SaXem3WaTNJlSdFEkaVDe9F
console.log(dataId); // displays 1
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "You will not be able to recover this Tournament!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel pls!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
$.ajax(
{
type: 'POST', // I tried with DELETE too
url: '{{ url('/tournaments/') }}' + dataId,
data: inputData,
success: function (msg) {
console.log('success'); // It triggers!
$tr.find('td').fadeOut(1000, function () {
$tr.remove();
});
swal({
title: "Deleted!",
text: "Tournament has been deleted.",
confirmButtonColor: "#66BB6A",
type: "success"
});
},
error: function () {
swal("Oops", "We couldn't connect to the server!", "error");
}
}
)
}
else {
swal({
title: "Cancelled",
text: "Your Tournament is safe :)",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
});
});
Here is my contoller:
public function destroy(Tournament $tournament)
{
$tournament->delete();
return response(['msg' => 'Product deleted', 'status' => 'success']);
}
Before, I had it working without AJAX so route is OK.
Everything works fine (modals shows) but it doesn't delete my tournament
I am new to JS / JQuery, so I don't know what's going on.
Any idea how to fix it?
You need to pretty much change all your references to use class as a selector. I am only guessing on the Laravel stuff, also make your id's unique (I appended tournament Id), but it all needs to change to class:
Guessing on this, not familiar with the syntax
#foreach($tournaments as $tournament)
<tr id="line{{$tournament->id}}" data-id="{{$tournament->id}}" class="parentTr">
<td>
{{ $tournament->id }}
</td>
<td>{{ $tournament->owner->name}}</td>
<td class="text-center">
{!! Form::open(['method' => 'DELETE', 'class' => 'formDeleteTourament', 'action' => ['TournamentController#destroy', $tournament->id]]) !!}
{!! Form::button( '<i class="glyphicon glyphicon-remove"></i>', ['class' => 'btn text-warning-600 btn-flat btnDeleteTournament', 'data-id' => $tournament->id ] ) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
Javascript Changes
<script>
$(function () {
$('.btnDeleteTournament').on('click', function (e) {
var inputData = $(this).parents('.formDeleteTourament').serialize();
var dataId = $(this).data('id');
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "You will not be able to recover this Tournament!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel pls!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
$.ajax({
// I don't you know if you have to escape the inner
// quotes or not, that is a framework syntax thing
url: '{{ url('/tournaments/') }}',
type: 'POST',
// Just include the id in a post data object
data: { form: inputData, id: dataId },
success: function (msg)
{
console.log(msg);
$tr.find('td').fadeOut(1000, function() {
$tr.remove();
});
swal({
title: "Deleted!",
text: "Tournament has been deleted.",
confirmButtonColor: "#66BB6A",
type: "success"
});
},
error: function()
{
swal("Oops", "We couldn't connect to the server!", "error");
}
});
}
else {
swal({
title: "Cancelled",
text: "Your Tournament is safe :)",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
});
});
</script>