Laravel Ajax delete record with button - ajax

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()

Related

toggle active/inactive states in Laravel

I want to update active and inactive status in laravel with toggle. Status show perfectly. But controller doesn't work. Here
is my code.
blade file
#foreach($data as $srial => $row)
<tr>
<td>{{$row->name}}</td>
<td>
<input data-id="{{$row->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $row->status ? 'checked' : '' }}>
</td>
</tr>
#endforeach
<script>
$(document).ready(function(){
$('.toggle-class').change(function () {
let status = $(this).prop('checked') === true ? 1 : 0;
let userId = $(this).data('id');
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('/changeStatus') }}',
data: {'status': status, 'user_id': userId},
success: function (data) {
console.log(data.message);
}
});
});
});
</script>
Controller
public function changeUserStatus(Request $request)
{
$file=DB::table('students')->where('id',$id)->first();
$user=$file->status;
$task ['status']= $request->user_id;
$data=DB::table('students')->where('id',$request)->update($task);
}
Route
Route::get('/changeStatus', 'AdminController#ChangeUserStatus')->name('/changeStatus');
Try bellow query:
public function changeUserStatus(Request $request)
{
DB::table('students')->where('id', $request->user_id)->update(['status' => $request->status]);
}
Where condition is wrong, need to pass user id and status in update.
and in view, ajax type must be post
$(document).ready(function(){
$('.toggle-class').change(function () {
let status = $(this).prop('checked') === true ? 1 : 0;
let userId = $(this).data('id');
$.ajax({
type: "POST",
dataType: "json",
url: "{{ route('/changeStatus') }}",
data: {'status': status, 'user_id': userId},
success: function (data) {
console.log(data.message);
}
});
});
});
Route must be post type
Route::post('/changeStatus', 'AdminController#ChangeUserStatus')->name('/changeStatus');

ID received from post - send via ajax

I would like to read the post id from html and send it via AJAX to the controller. How can I get the post ID ($post->id) and transfer it via AJAX? Or is there a better solution to save the post seen by the user?
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" class="row waypoint">
</div>
#endforeach
This is my AJAX code:
$('.waypoint').waypoint(function() {
$.ajax({
url: '/posts/view',
type: "post",
data:
success: function(request){
console.log(request);
},
error: function(response){
console.log(response);
},
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}, {
offset: '100%'
});
Get the id from the focused waypoint.
let waypoint_id = this.getAttribute('id'); // something like 'post_container_1'
Get only the string after the _
let post_id = waypoint_id.split("_").pop(); // something like '1'
in ajax() function
data: {
post_id: post_id
}
You could add a data-id attribute like so:
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" data-id="{{$post->id}}" class="row waypoint">
</div>
#endforeach
And then access it using the attr()
$('.waypoint').waypoint(function() {
let post_id = $(this).attr('data-id'); //this specifies the particular post row in focus.
$.ajax({
url: '/posts/view',
type: "post",
data: {post_id: post_id}
//and so on.
});
}, {
offset: '100%'
});

Passing muliple options to controller in laravel

I'm trying to send multiple selected options to my controller but i can't
Code
route
Route::post('/spacssendto/{id}', 'ProductController#spacssendto')->name('spacssendto');
ajax
$("body").on("click", ".sendspacsdatato", function(e){
e.preventDefault();
var id = $("#product_id").val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'subspecification_id': $('.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
controller
public function spacssendto(Request $request, $id) {
dd($request->all());
}
my form (output)
<form method="POST" action="http://sieffgsa.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">ram</div>
<div class="col-md-6">
<select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">
<option value="3">2gig</option>
<option value="4">4gig</option>
</select>
</div>
<div class="col-md-2">
<label for="">Actions</label><br>
<button type="button" id="sendspacsdatato" class=" sendspacsdatato btn btn-xs btn-success">Save</button>
</div>
</form>
PS: This form printed by Ajax in my view so it means there is several
more forms involved (the same way) that's why i mostly used classes
and not id's. Yet when I hit save button I will get 3 times repeat in
network (if i have 3 form)
Errors
Error 500 in network
dd result:
array:3 [
"_token" => "DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16"
"product_id" => "15"
"subspecification_id" => null
]
Question
How can I pass my multiple options (selected) to controller?
UPDATE
Thanks to Seva Kalashnikov I fixed the problem just for helping others I'll publish final results here so you can have full code, hope it helps.
javascript
$(document).ready(function() {
$("body").on("click", ".sendspacsdatato", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.').fadeIn().delay(6000).fadeOut();
},
error: function (data) {
console.log('Error!');
}
});
});
});
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$product = Product::find($request->product_id);
$product->subspecifications()->sync($request->subspecifications, false);
}
You need to get select with css class subspecifications inside the same form element
'subspecification_id': $(this).closest('form').find('select.subspecifications').val()
Try this code:
$('.sendspacsdatato').click(function() {
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': form.find('input[name=_token]').val(),
'product_id': id,
'subspecification_id': form.find('select.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});

Delete\Add Row with AJAX (Secure way)

i am new to Laravel and trying to find way to delete or add row with AJAX request.
Let's say i have PostController and i want to delete one of my post.
So in the PostController there will be destroy function :
public function destroy($id)
{
Posts::find($id)->delete();
}
Now, how i can send from a view AJAX Request to Controller and use this destroy method in secure way.
This works for me,
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>
OK, This works for me.
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>

Confirm Before Deleting with Sweet Alert Laravel 5.5

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.

Resources