Confirm Before Deleting with Sweet Alert Laravel 5.5 - laravel

I want the sweet alert box to go out without deleting.
But id not found for ajax
Route
Route::get('room/delete/{id}', 'RoomList#destroy')->name('roomdelete');
View File rooms-list.blade.php
#foreach($rooms as $room)
<tr>
<td>{!! $room->room_id !!}</td>
<td>{!! $room->hotel_id !!}</td>
<td>{!! $room->room_name !!}</td>
<td>
<i class="fa fa-close text-danger"></i> </td>
</tr>
#endforeach
SweetAlert Js Code above
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('room/delete')}}",
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Controller File RoomList.php
public function destroy($id) {
$rooms = Room::find($id);
$rooms->delete();
return redirect()->back()->with('deleted', 'Delete Success!');
}
Clicking on the delete button does not work
Best Regards

First thing first, you have a GET route and you are sending a POST request here so first change your ajax method to GET like this:
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "GET",
url: "{{url('room/delete/')}}+id", // since your route has /{id}
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Also I'm not sure about $(document).on('click', '.button', function (e) I guess it should be like this:
$('.button').on('click', '.button', function (e)
Let me know If you still have any issue.

Related

How can I delete using ajax in laravel?

BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();

I want to delete data without refreshing whole page using ajax

I am new at Laravel, I am trying to delete data with ajax, when I click to delete button, the page is refreshing but data is deleting perfectly but that should not be reloaded.
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
return back();
}
HTML view
<a href="{{route('digitizing.delete',$digitizing->id)}}"
class="btn btn-danger" onclick="deleteConfirmation({{$digitizing->id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
Swal.fire({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('digitizing/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
**Delete wants a get method because you have to give only ID to delete.**
**WEB.PHP**
Route::get('digitizing/delete/{id}','YourController#destroy');
**SCRIPT**
let id = $('#my_id').val();
$.ajax({
type: 'GET',
url: "{{url('digitizing/delete')}}/" + id,
data: {
_token: '{{csrf_token()}}',
},
success: function () {
alert('Successfully Deleted');
}
}).fail(function(){
console.log('problem with route = digitizing/delete');
});

Ajax page is reloading after storing data

i am triyng to save data but my page is reloading with json message on next page, how can i stop reloading page.
Ajax Code:
jQuery(document).ready(function($) {
$("#add-data").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Submit Button:
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
Store Controller:
after saving which is working fine:
return response()->json([
'status' => 'success',
'msg' => 'New esecond has been saved'
]);
It is because of you are trying to post the data to form .
If you use button type = "submit" it will redirect you to somewhere .
You should avoid using type = "submit" .
Instead use the type = "button"
<button type = "button" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
And achieve it by using click event of the button .
then get it in jquery .
$("#add-data").click(function (event) {
//Your code here
}
You can try this instead of prevent default. The reload happen, because you use form submit event.
$('#add-data').submit(false);
If you want to use prevent default, then use click event of the submit button to perform the action.
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
}
Remove dataType: 'json' as you're already returning JSON otherwise your button seems perfect.
Try this
jQuery(document).ready(function($) {
$("#add-data").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Add "return false;" in the end of your submit callback..
As "add-data" is ID of your button, for your example it couldn't retrieve a submit event. That's because it submitted and didn't prevented.
So you can write something like this:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({ ... });
return false; // <<< THE THING
});
Or just do that with binding an click event on button (not for submit event on button)
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({ ... });
});
With this you can leave button type, and don't need to change that to type="button".

Laravel Ajax delete record with button

I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()

Refresh jQuery datatable table

Been plenty of questions about this but I never found one that worked for me. I have a plain and simple HTML table whos body is being filled with rows from an AJAX call.
Then I want to update the table with DataTable plugin but it does not work.
I have a HTML table that looks like this:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In my jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
And finally my on dropdownlist change function
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
The append and so on has been modified to shorten it down, etc so do not focus too much on it.
Basically the question is how to update the table, I can do my AJAX and add new data to the table fine, but the datatable plugin does not update with it.
I've tried other things like
.fnDraw(false);
But it does nothing
While I get an JSON error from
fnReloadAjax()
Any clues on just how to refresh the table?
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO
I Know this is an old post, but I've just investigated about the problem and I find the easiest way to solve it in DataTable man pages: https://datatables.net/reference/api/ajax.reload%28%29
All you need to call table.ajax.reload();
var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});
I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
From version 1.10.0 onwards you can use ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Keep in mind to use $('#myTable').DataTable() and not
$('#myTable').dataTable()

Resources