Delete Image through Ajax without reloading page laravel - php

I want to delete Image without reloading a page through Ajax but every time when I delete the Image, first it's not deleted but when I refresh the page the image can delete.
app.js:
$('.delete-image').on('click', function(e){
e.preventDefault();
let id = $(this).attr('data-id');
bootbox.confirm("Are you sure you want to delete this company?", function(result){
if(result){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type : 'DELETE',
url : '/albums/delete',
data : {
id : id,
},
success : function(response){
if(response){
$(this).parents('.album').slideUp().remove();
}
}.bind(this)
})
}
}.bind(this));
});
AlbumController:
public function deleteImage(Request $request){
$album = Album::find($request->id);
if($album->delete())
return response()->json(true);
else
return response()->json(false);
}
blade.php:
#extends('layout.app')
#section('content')
<div class='medium-3 columns end'>
<div class="row text-center">
#foreach($album as $albm)
<h4>{{$albm->name}}</h4>
<h4>{{$albm->description}}</h4>
<a href="/albums/{{$albm->id}}" class="btn btn-link">Edit
<img class="thumbnail" src="/storage/store/{{$albm->cover_image}}" alt="{{$albm->name}}">
</a>
Delete
<br>
#endforeach
</div>
</div>
#endsection
Route:
Route::delete('/albums/delete', 'AlbumController#deleteImage');

$(this).parents('.album').slideUp().remove();
You have no elements with class="album" so the selector won't match anything.

After delete success response just delete its parent div that has class row
$('.delete-image').on('click', function(e){
e.preventDefault();
let id = $(this).attr('data-id');
let parentDiv = $(this).closest('div.row');
bootbox.confirm("Are you sure you want to delete this company?", function(result){
if(result){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type : 'DELETE',
url : '/albums/delete',
data : {
id : id,
},
success : function(response){
if(response){
$(parentDiv).remove();
}
}.bind(this)
})
}
}.bind(this));
});

Related

jQuery: hide table row

This is the function that is called when button delete is pressed. After confirmation of delete, I want to hide the delete tr :
function delete_confirmation(id) {
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "To delete this patient!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: localStorage.getItem("base_url") + '' + 'index.php/Patient_ws/delete/',
timeout: 4000,
type: "POST",
data: ({id: id}),
}).done(function () {
$tr.remove();
})
.fail(function () {
swal({
title: ' erreur in server, try later...',
type: 'warning'
})
})
} else {
swal("Patient not deleted");
}
});
}
Html markup:
<a href="#" class="btn btn-danger btn-xs" onclick="delete_confirmation(<?php echo $patient->id_personne;?>)">
<i class="fa fa-trash-o"></i> Delete </a>
I want to hide tr - please help.
There is no explicit this in an onclick function unless you pass it in from the html. Try console.log(this) will see it is probably Window and not the element
Since you are already using jQuery I would suggest also using it for the event listener and moving the php output to a data attribute
HTML
<a class="delete-row-btn btn btn-danger btn-xs"
data-id="<?php echo $patient->id_personne;?>">
JS
$(document).on('click','.delete-row-btn', delete_confirmation)
function delete_confirmation(event) {
event.preventDefault();
// now `this` is the button
var id = $(this).data('id')
var $tr = $(this).closest('tr');
// all else should be same
swal({
.....
}

Delete row with ajax and delete the record on page too

I'm trying to remove the record in database via ajax. In the same time I want to delete also the record from the page. So I have this in my HTML
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<a href="?delete='.$row['id'].'" class="del">
<i class="fa fa-trash "></i>
</a>
</div>
</div>
</div>
</li>
</ul>
This is inside the loop which display all records on page. This is the ajax function
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
And my delete.php is simple delete query
$stmt = $pdo->prepare("DELETE FROM comment where id = :id");
$stmt->bindParam(':id', (int)$id, PDO::PARAM_INT);
$stmt->execute();
Current error is from the ajax when I click on delete on this line index.php:183 Uncaught TypeError: Cannot read property 'replace' of undefined
Uncaught TypeError: Cannot read property 'replace' of undefined
The ajax part is from tutorial since I'm very unfamiliar with js/ajax.
What can be the problem here?
In your function $(this) = <a href="?delete='.$row['id'].'" class="del">.
var parent = $(this).parent(); = <div class="comment-head">
which has no ID. Thus attr('id') returns undefined.
You can select the ul element this way:
var parent = $(this).closest('ul.comments-list.record');
How about this code: (make full use of jquery)
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<i onclick="del(<?=$row['id']?>)" class="fa fa-trash "></i>
</div>
</div>
</div>
</li>
your jquery becomes:
function del(i)
{
$.ajax({
type: 'get',
url: 'delete.php',
data: {'ajax':1,'delete':i},
success: function() {
get_list();
}
});
}
function get_list()
{
//make ajax call to get data from php
}
You are getting undefined because the parent you are fetching is this one:
<div class="comment-head">
As you can see that does not have an id. That is why you are getting undefined.
For reference, I do not believe that there is a replace() method in jQuery. What you might be looking for is a replaceWith() method. Please refer to the documentation for more information.
I do not believe that you need to do a replace anywhere. From what I can understand, you want to pass the row[id] as a parameter on your AJAX call. Instead of trying to do a replace, use data as shown below:
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style>
#comments-list {
border: 1px solid black;
}
</style>
<ul id="comments-list" data-id="1" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">Me</h6>
<a href="?delete=1" class="del">
click here
</a>
</div>
</div>
</div>
</li>
</ul>
<script>
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
// Grab the id
var commentsBlock = $('#comments-list');
var id = commentsBlock.data('id');
console.log(id);
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + id,
success: function() {
commentsBlock.slideUp(300,function() {
commentsBlock.remove();
});
}
});
});
});
</script>

PHP Laravel : Delete Data using Ajax

I want to delete some data from database using ajax.. I've done the following steps to run..But while I was trying to delete it's shows following Error:
Failed to load resource: the server responded with a status of 404
(Not Found)
Here is my route:
Route::post('/delete/{id}',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
Here is the controller:
public function delete($id)
{
Item::find($id)->delete();
return Redirect::back();
}
And here is my view page:
<html>
<head>
<title> Item List</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3> List Of Courses </h3></br>
<table class="table table-striped table-bordered dataTable" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Title</td>
<td>Description</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($items as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->title }}</td>
<td>{{$row->description}}</td>
<td>
<button type="button" onclick="deleteItem({{ $row->id }})" id="Reco" class="btn btn-danger">Delete</button>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
<script>
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/delete/'+id,
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
If anyone find the error I've done, hope you'll help me to find it out.
Generally passing parameter while deleting is not a good idea. since we can delete the data through url e.g /delete/4 while you may want to delete only after clicking the delete button.
$.ajax({
type: "POST",
url: "{{url('/delete)}}",
data:{id:id}
success: function(result) {
console.log(result);
}
});
route:
Route::post('/delete',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
and, the controller
public function delete(Request $request)
{
$id=$request->id;
Item::where(['id'=>$id])->delete();
return Redirect::back();
}
Try this code:
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url:"{{url('delete')}}",
data:{id:id},
success: function(result) {
location.reload();
}
});
}
try this code
function deleteItem(id) {
var _token = $("input[name='_token']").val();
$.ajax({
type: "POST",
url: '/task/'+id,
data: '_method=DELETE&_token=' + _token,
success: function (result) {
console.log(result);
}
});
}
Try this:
$.ajax({
type: "POST",
url: url('/delete'), // The correct way to call ajax function in laravel
data:{
id: id
},
success: function(result) {
console.log(result);
}
});
You can set a method destroy in your controller which laravel automatically uses for deleting. It accepts id.
public function destroy($id){
Item::find($id)->delete();
echo 'Deleted Successfully.';
}
for ajax just send a method delete with your token.
jQuery.ajax({
url:'your-controller-route/id',
type: 'post',
data: {_method: 'delete', _token :token},
success:function(msg){
// do stuff
}
});

How to Select Custom line AJAX in Laravel

My problem is that when I delete a line we can only do I delete a row and jQuery practice for other lines will not be executed.
<script>
$('#destroy').on('click', function (e) {
e.preventDefault();
var token = $('input[name="_token"]').attr('value');
var id = $('#destroy').data("id");
$.ajax(
{
url: "{{ url('/category') }}" + '/' + id + '/delete',
type: 'post',
dataType: "JSON",
data: {"id": id, '_token': token},
success: function (data) {
alert(data.msg)
}
});
console.log("It failed");
});
</script>
line:
<tr id="destroy_">
<td>
<a id="destroy" data-id="{{$cat->id}}" href="#">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
<td>
<a href="{{action('categoryController#update',[$cat->id])}}">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
</td>
<td>
<a href="{{action('categoryController#show', [$cat->id])}}">
{{$cat->category}}
</a>
</td>
<th class="text-right">{{$cat->id}}</th>
</tr>
Using ID's for actions that are repeated in a table is a bad idea if you don't name them dynamically. Either way I suggest using anything other than an ID, for example a custom data attribute. So use this for your delete links:
<a data-delete data-id="{{$cat->id}}" href="#">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
And in your JS code instead of #destroy you can now use the following selector to match them:
$(document).on('click', '[data-delete]', function (e) {
e.preventDefault();
var token = $('input[name="_token"]').attr('value');
var id = $(this).data("id");
$.ajax(
{
url: "{{ url('/category') }}" + '/' + id + '/delete',
type: 'post',
dataType: "JSON",
data: {"id": id, '_token': token},
success: function (data) {
alert(data.msg)
},
error: function () {
// Also the failed request should be handled here
// not below the ajax call because it's asynchronous
console.log("It failed");
}
});
});

Symfony delete ajax

I have a problem when I want delete a register with Ajax and Symfony, in template Twig.
<tbody>
{% for entity in entities %}
<tr>
<td>
<a class="delete btn btn-danger btn-xs glyphicon glyphicon-trash" data-playgroup-id="{{ entity.id }}" ></a>
</td>
</tr>
{% endfor %}
</tbody>
Ajax:
$(document).ready(function() {
$(".delete").click(function(){
var pid = $(this).attr("data-playgroup-id");
bootbox.confirm("Are you sure?", function(result) {
if(result){
$.ajax({
url: '{{path('playergroup_delete', { 'id': pid}) }}',
type: 'delete',
success: function(result) {
console.log('Delete');
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
});
I receive the next error:
Variable "pid" does not exists.
Thanks!
As MouradK say you ar passing a variable in a twig function (server side) and you are getting this variable using javascript (client side).
to solve this do something like this :
$(document).ready(function() {
$(".delete").click(function(){
var pid = $(this).attr("data-playgroup-id");
bootbox.confirm("Are you sure?", function(result) {
url = '{{path('playergroup_delete', { 'id': 0}) }}';
url = $url.replace("0",pid);
if(result){
$.ajax({
url: url,
type: 'delete',
success: function(result) {
console.log('Delete');
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
});
It means that you did not pass the pid variable to your Twig template.
Pass it trough the controller and you'll be fine
The error is :
You are trying to set a variable comming from the client (javascript) in your twig template (which is a server side).

Categories