How can I delete using ajax in laravel? - ajax

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

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');

how to retrieve data from DB using AJAX

I want to retrieve data from DB to my user Dashboard. User Identify using Contact No.
I run AJAX query to retrieve all adds. its running well.
but I need to retrieve data under his user ID (ContactNo). here I add AJAX code.
user data avaiable in AUTH -> {{ Auth::user()->ContactNo }}
$(document).ready(function($){
//alert("jquery running");
getAll();
});
//getting all rows from the database
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
</script>
You need to pass de contactNo parameter in your query:
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
data: {
contact_no: contactNo,
},
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
So in your controller now you can filter:
public function getData(Request $request){
$contact_no = $request->contact_no;
$query = DB::table('my_table');
if($contact_no){
$query->where('contact_no',$contact_no)
}
return response()->json($query->get());
}
Or directly use the session of the user:
public function getData(Request $request){
$contact_no = Auth::user()->ContactNo;
$query = DB::table('my_table');
$query->where('contact_no',$contact_no)
return response()->json($query->get());
}
public function Myadds(){
try{
return add::where('userID', Auth::user()->ContactNo)->get();
}catch(Exception $e){
return 'false';
}
}

Wishlist heart icon color change based on selection in laravel 5.7

my requirement of coding is "when i am click on wishlist heart icon. if i am not login, then i am going to login page & If i am login then fa-fa heart color is change orange when i am added item in wishlist & grey when it remove. i am sending json response refer my coding.
controller:
public function add_to_wishlist(Request $req)
{
$userId=Session::get('userid');
if(empty($userId))
{
return response()->json(['status'=> 1]);
}
else
{
$checkWishlist=DB::select('select * from wishlist where user_id=? && product_id=?',[$userId,$req->sub_id]);
if($checkWishlist)
{
DB::table('wishlist')->where('user_id',$userId)->where('product_id',$req->sub_id)->delete();
return response()->json(['status'=> 2]);
}
else
{
DB::table('wishlist')->insert(['user_id'=>$userId,'product_id'=>$req->sub_id]);
return response()->json(['status'=> 3]);
}
}
}
blade code:
<input type="text" name="status" id="status" class="form-control status" value="">
<a class="sub" data-id="{{$value->sub_id}}" href="#"><i class="fa fa-heart" style="float:right;color:grey"></i></a>
jquery and ajax:
<script type="text/javascript">
$(document).ready(function(){
$('.sub').click(function(e) {
var sub_id=$(this).attr('data-id');
var input=$(this).prev();
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/add-to-wishlist') }}",
method: 'get',
data: {
sub_id: sub_id,
},
success: function(result){
input.val(result.status);
}});
});
});
</script>
First add dataType:'JSON'
Then add some conditions in success function:
$('.sub').click(function(e) {
var input = $(this);
...
...
$.ajax({
...
success: function(result){
var status = result.status;
input.val(status);
if(status==1){
//Not logged in
window.location.href ="path/to/login";
}else if(status==2){
//Delete
input.next().css('background','gray');
}else{
//Logged in
input.next().css('background','orange');
}
}});
});
});

Deleting record using laravel and vue js

I'm stuck in making a delete method using vue js and laravel. I tried to add a value to the href attribute using laravel resource and pass an id as a second parameter but when I click on it and display the id on console it shows the same id to all data which is incorrect.
Sample blade:
<a id="deleteRecord" data-id="{{$project->id}}" #click.prevent="deleteRecord" class="btn btn-circle btn-icon-only btn-danger" href="{{ route('projects.store', $project->id) }}">
<i class="icon-trash"></i>
</a>
Vue method:
deleteRecord: function(id) {
var dataId = $('#deleteRecord').attr('href')
console.log(dataId);
}
Inside of your method deleteRecord:
this.$http.delete(url)
.success(function(response) {
console.log(response)
})
.error(function(errors) {
console.log(error)
});
Or using axios inside of your method
axios.delete(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get it now. I'll just post it here to help others also.
deleteRecord: function(id) {
var url = "projects" + "/" + id;
$.ajax({
url: url,
type: 'DELETE',
data: { "_token": "{{ csrf_token() }}" },
success: function(response) {
//do some success stuff here..
}
});
}

Using Ajax to implement controller method which is passed an ID

I have a button that toggles a boolean value in my DB table. It works but reloads the page each time, so I'd like to toggle it using AJAX. I'm not sure how to do an AJAX post request that can provide the controller with the ID it needs. This is what I have so far:
TaskController Method:
public function updateCompleted($id)
{
$task = Task::findOrFail($id);
if($task->completed) {
$task->completed = false;
} else {
$task->completed = true;
}
$task->save();
Session::flash('message', 'Task updated!');
return redirect('tasks');
}
Button used to toggle (in this case, the first task with ID of 1):
{{ Form::open(array('action' => array('TaskController#updateCompleted', $task->id))) }}
{{ Form::hidden('_method', 'PATCH') }}
#if ($task->completed)
{{ Form::button('<span class="glyphicon glyphicon-ok"></span>', array('class'=>'btn btn-danger', 'type'=>'submit')) }}
#else
{{ Form::button('<span class="glyphicon glyphicon-remove"></span>', array('class'=>'btn btn-danger ajaxSubmit', 'type'=>'submit')) }}
#endif
{{ Form::close() }}
AJAX that doesn't work...
$('.ajaxSubmit').click(function(e) {
e.preventDefault();
$.ajax({
url: 'tasks/complete/{id}',
type: 'POST',
success: function(response)
{
console.log("working");
}
});
});
And route:
Route::patch('tasks/complete/{id}', 'TaskController#updateCompleted');
How do I get the Ajax to work? Thanks
try this
add the id in hidden input with id of "myid" for example
$('.ajaxSubmit').click(function(e) {
var data = $("#myid").val();
e.preventDefault();
$.ajax({
url: '/tasks/complete',
type: 'POST',
data: data,
success: function(response)
{
console.log("working");
}
});
});
do this
Route::post('tasks/complete', 'TaskController#updateCompleted');
don't forget CSRF .

Resources