Laravel 5.3.6 Ajax delete gives 404 error - ajax

Busy learning Laravel and a bit (very) confused.
I have a page with datatable and a button to delete a record.
I want this button to delete the record with ajax.
My js code:
$(document).on('click', '.deleteBtn', function() {
var url = $(this).attr('href');
swal({
title: "Are you sure?",
text: "You will not be able to recover this business type file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel pls!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax ({
url: url,
type: 'DELETE',
success: function () {
swal("Deleted!", "Your business type has been deleted.", "success");
}
});
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
return false;
});
In the Routes/api.php file:
// business type
Route::delete('businessTypes/{business_type_id?}/destroy', ['as' => 'businessTypes.destroy', 'uses' => 'BusinessTypeController#destroy']);
Route::any('businessType', 'ApiBusinessTypeController#businessTypeData', ['except' => ['destroy']]);
In Routes/web.php:
Route::get('businessTypes/create', ['as' => 'businessTypes.create', 'uses' => 'BusinessTypeController#create']);
Route::get('businessTypes/{business_type_id}-{slug?}', ['as' => 'businessTypes.show', 'uses' => 'BusinessTypeController#show']);
Route::resource('businessTypes', 'BusinessTypeController', ['except' => ['show', 'create', 'destroy']]);
When I click the delete button I get the error: 404 Page not Found.
What am I doing wrong?

Related

Sweet Alert 2 redirect on CANCEL

I am writing a project in laravel, at my current point in the workflow I want the user to be able to click a button to publish or remove an event from the current list.
I am using SA2 to stop the submission to the route before it happens, if the user hits OK, then everything goes as planned, when the user hits cancel, I want to redirect back to the page.
The issue I am running in to is that when the user hits cancel, the redirect to the page happens anyway...
function warnRemove(linkURL) {
swal({
title: 'Are you sure?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: 'D6B55',
confirmButtonText: 'Yes, remove it!'
}).then(function () {
window.location = linkURL;
});
}
function warnPublish(linkURL) {
swal({
title: 'Are you sure?',
type: 'warning',
text: 'This event will go live on the screen after next refresh.',
showCancelButton: true,
confirmButtonColor: 'D6B55',
confirmButtonText: 'Yes, publish it!'
}).then(function () {
window.location = linkURL;
});
}
$('.remove').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
let linkURL = $(this).attr("href");
warnRemove(linkURL);
});
$('.publish').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
let linkURL = $(this).attr("href");
warnPublish(linkURL);
});
You will need to use the callback with an isConfirm boolean:
function(isConfirm) {
if (isConfirm) {
// do confirmed things
}
}
From the docs:
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
// redirect only if true
if (result.value) {
// redirect here
}
})

how to use pjax and sweetalert confirmation to delete row in laravel 5.3

I use sweetalert to get confirm for delete rows from user, the code for confirmation is
$('.delete').click(function(){
var formClass = $(this).attr('id');
$("form."+ formClass).submit(function( event ){
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
}, function() {
form.submit();
});
} else {
swal("Cansel", "Not deleted :)", "error");
}
});
});
});
and this code for use pjax to have an ajax request in laravel
$(document).on('pjax:send', function() {
$('#loading').show();
$("#pjax-container").css({"opacity": "0.3"});
})
$(document).on('pjax:complete', function() {
$('#loading').hide();
$("#pjax-container").css({"opacity": "1"});
})
$(document).on('submit', 'form[form-pjax]', function(event) {
$.pjax.submit(event, '#pjax-container')
});
And the html form is:
<form action="{{ route('admin.comments.destroy',[$comment->id]) }}" class="inline-div comment-{{ $comment->id }}" method="post" form-pjax>
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-danger btn-opt delete" id="comment-{{ $comment->id }}"><span class="glyphicon glyphicon-trash"></span></button>
By this code i haven't an ajax request.
Instead of "form.submit();" What to write?
From what I can see, you don't need to use pjax for this at all. You can delete a record from database asynchronously, simply using an ajax request. Here is how I would go about doing this:
In the code below, when the user clicks on the delete link, an alert would be presented to him. If he confirms the delete action, then the function deleteFromDB would be called which is responsible for sending an ajax request to the server.
$('.delete').click(function(){
var formClass = $(this).attr('id');
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
deleteFromDB(formClass);
} else {
swal("Cancel", "Not deleted", "error");
}
});
});
The mentioned function is defined as below:
function deleteFromDB(formClass) {
var url = "http://example.com/delete/this/record";
var form = $("form."+ formClass);
var formData = new FormData();
form.find("input[name]").each(function(index, input) {
formData.append(input.name, input.value);
});
$.post(url, formData).done(function(data) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
});
});
}
It finds all the inputs that have a name attribute and appends each to a FormData object. Then a post ajax request is sent to the server and when the request is done, another alert showing the success of deletion shows up.
Pay attention here not to show the success alert before deleting the record (as you were doing in the above code), because then if something goes wrong during the request, i.e. the record could not be deleted for some reason, you would be able to show that error to the user.

Delete the record using sweetalert js in codeigniter using ajax

I want to delete the record using sweetalert js.
This is my view file:-
<a class="action-link delete" title="delete" href="#" onclick="confirmDelete()"> <i class="glyphicon glyphicon-trash"></i> </a>
This is my function:-
function confirmDelete(){
var id=1;
swal({
title: 'Are you sure?',
text: "You won't be able to delete this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
closeOnConfirm: false
},function (isConfirm) {
$.ajax({
url: base_url+"admin/mycontroller/delete",
type: "POST",
data: {"id":id},
dataType:"HTML",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}
This is my controller delete function
public function delete(){
$id = $this->input->post('id');
$data[ 'status'] = '0';
$where = array( 'id' => $id );
$this->model->update( $this->tablename , $data , $where );
}
But not delete the data. Please help me out.
Edit: url as below
function confirmDelete(){
var id=1;
swal({
title: 'Are you sure?',
text: "You won't be able to delete this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
closeOnConfirm: false
},function (isConfirm) {
$.ajax({
url: <?=base_url()?>"admin/mycontroller/delete",
type: "POST",
data: {"id":id},
dataType:"HTML",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}

Cakephp: multiply jquery binds conflict

I have a page on which i have placed several jquery sliders, some checkboxes and radio buttons.
I post is created on slidestop, change of checkboxes, change or radio buttons. This works great.
On this same page there is a table displayed with this information and in the buttons which are outbound links, i have placed id's which are posted to another controller to track the outbound clicks with their id's.
When the button is clicked a post with the id is done using jquery to this clicks controller.
This works great when the sliders, checkboxes, radio buttons aren't used. As soon as one of those elements are touched the post to this clicks controller on the buttons click doesnt work anymore.
This is what the javascript looks like:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$(".btn").bind("click", function (event) {
$.ajax({
async: true,
data: "id=" + $(this).attr("id"),
dataType: "html",
type: "POST",
url: "\/clicks"
});
return false;
});
$("#saveForm").bind("slideStop", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
$(".checkbox").bind("change", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
$(".radio").bind("change", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
});
//]]>
</script>
I think it's caused by the multiple posts on the same page but i'm not sure. I have been trying to fix this the whole day but couldn't find a solution.
Update:
I found what is causing the other function to fail.
$this->Js->get('#saveForm')->event(
'slideStop',
$this->Js->request(
array('action' => 'index', 'controller' => 'abonnements'),
array(
'update' => '#resultaat',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST',
'before' => '$("#loading").attr("style", " ")',
'complete' => '$("#loading").attr("style", "display:none")'
))
);
The action for the .btn which is displayed in the #resultaat table is broken when the update is done by the slideStop action.
This is how the button looks like:
<td>
<?php echo $this->Html->link('Meer Info',
$link,
array('class' => 'btn btn-primary btn-block',
'target' => '_blank',
'id' => $abonnement['Abonnement']['id']
)
);
?>
</td>
The id is needed.
I have solved the issue by placing the jquery code for the button click on the element which is updated by the other jquery function. Somehow it lost the bind when the slider updated the element in which another bind is placed.

Laravel 4 AJAX CSRF Token Mismatch (with _token)

I'm attempting to do a simple (soft) delete on my model from a customized implementation of the frozennode/administrator package. Whenever I hit my route via ajax, the application throws a TokenMismatchException.
I've tried with both cookie and file drivers set in the session config.
I have confirmed the _token is being submitted with the ajax request. Commenting the csrf filter out altogether allows me to successfully delete the record. I'm using the out-of-the-box csrf filter.
I'm also using the excellent Sweet Alert plugin, though that doesn't appear to be related.
routes.php:
//CSRF protection in forms
Route::group(array('before' => 'csrf'), function()
{
//Delete Item
Route::post('{model}/{id}/delete', array(
'as' => 'admin_delete_item',
'uses' => 'Frozennode\Administrator\AdminController#delete'
));
...
Blade template:
<a href="" class="btn btn-danger" id="delete-item-button" data-token="{{ csrf_token()}} ">
<i class="fa fa-trash"></i>
<span>
Delete
</span>
</a>
Javascript:
Excuse my hellishness $.post is what's relevant.
$('#delete-item-button').on('click', function (e) {
e.preventDefault();
var token = $(this).data('token');
swal({
title: "Delete this record?",
text: "There's no undo!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function () {
$.post(
window.location.pathname + "/delete",
{"_token" : token},
function(){
swal({
title: "Deleted!",
text: "The record has been deleted.",
type: "success"
},
function () {
window.location.href = 'http://www.example.com'
})},
"json"
);
});
});
Any help or guidance would be greatly appreciated.
Thanks!

Resources