Confirm delete dialog using ajax and bootstrap - ajax

I'd like to display a confirm delete dialog using Bootstrap v3 before deleting an entity.
My code works fine, but without confirm dialog. How can I do that?
{% for travel in pagination %}
<div class="col-sm-6 col-md-4" id="item-{{ travel.id }}">
//......
<a title="delete" href data-entity-id="{{ travel.id }}" class="button btn-mini red remove_item">Delete</a>
</div>
{% endfor %}
<script>
$(document).ready(function () {
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('travel_delete', {'id': entityId}),
success: function () {
//hide the block of item after delete success
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>
Edited
I tried this code. I'd like when clicking on delete link, pass the value of attr entity-id which is in the delete link, to the attr data-entity-id in delete button in the modal. How can I do that ?
error console:
Failed to load resource: the server responded with a status of 404 (Not Found)
<a title="delete" href data-toggle="modal" data-target="#myModal" entity-id="{{ travel.id }}" class="button btn-mini uppercase red">Sup ajax</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button data-entity-id="" type="button" class="btn btn-primary remove_item">Delete</button>
</div>
<script>
$(document).ready(function () {
$('#myModal').on('show.bs.modal', function () {
var entityId = $(this).attr('entity-id');
// set new value of attr data-entity-id but doesn't work
$('.remove_item').attr('data-entity-id', entityId);
});
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('frontend_travel_delete_favorite', {'id': entityId}),
success: function () {
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>

Try to do this:
<a id="delete-btn" title="delete" href data-toggle="modal" data-target="#myModal" data-entity-id="{{ travel.id }}" class="button btn-mini uppercase red">Sup ajax</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button data-entity-id="" type="button" class="btn btn-primary remove_item">Delete</button>
</div>
<script>
$(document).ready(function () {
$('#delete-btn').on('click', function () {
var entityId = $(this).attr('data-entity-id');
$('.remove_item').attr('data-entity-id', entityId);
});
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('frontend_travel_delete_favorite', {'id': entityId}),
success: function () {
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>

Related

Why my page gets refresh while deleting image on 'product edit page'?

VIEW FILE
<div class="col-sm-4">
<label>Other Images</label>
<div class="input-group control-group img_div form-group" >
<input type="file" name="image[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success btn-add-more" type="button">Add</button>
</div>
</div>
</div>
<div>#foreach($image as $image)
<p><img src="{{asset('/files/'.$image->images)}}" height="50px" id="{{$image->id}}" class="photo"/>
<button class="removeimg" data-id="{{$image->id}}" data-token="{{ csrf_token() }}">Remove</button></p>
#endforeach
</div>
AJAX
$(document).ready( function () {
$(document).on('click', '.removeimg',function(){
var confirmation = confirm("are you sure to remove this record?");
if (confirmation) {
var id = $(this).data("id");
// console.log(id)
var token = $(this).data("token");
var $obj = $(this);
$.ajax(
{
url: "{{ url('image/delete') }}/"+id,
type: 'post',
dataType: "JSON",
data: {
"id": id,
"_token": token,
},
success: function (res)
{
// $(this).parents('.photo').remove();
$obj.parents('.photo').remove();
console.log("it Work", res);
}
});
console.log("It failed");
}
});
});
CONTROLLER
public function imgdelete($id){
Image::find($id)->delete($id);
return response()->json([
'success'=> 'Image deleted successfully!'
]);
}
When I delete the image, page gets redirected to product listing. Page should not get refresh when I delete the image. Can you please help me with correction?? NOTE: This process takes place on editproduct page.
You can prevent the default event for the button:
$(document).on('click', '.removeimg',function(event){
event.preventDefault();
.....
});

How to update data on a page using ajax script?

There is a script that needs to update the data on the page in a specific div. But instead of updating, the block with the div is simply hidden and in order for it to appear again, you need to reload the page. The data comes in data, but here is $ ("# userPost" + id) .html (data); something doesn't work.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
// var formData = $('#EditPostForm'+id).serialize();
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#userPost"+id).html(data);
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
processData: false,
contentType: false,
});
});
And div
<div id="userPost{{$post->id}}">
#if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
#endif
<br>
#if($post->title)
<div class=" mr-1 mb-3 titleleft">
<h5 style="color: black"><b>{{$post->title}}</b></h5>
</div>
#endif
#if($post->message)
<div class="text-muted text-small margins" style="white-space: pre-wrap;">{{mb_strimwidth($post->message, 0, 600, " . . . Read more")}}</div>
#endif
#if($post->videoPost)
<div class="embed-responsive embed-responsive-16by9 mt-4 mb-2">
<iframe class="embed-responsive-item" src="{{$post->videoPost}}" allowfullscreen></iframe>
</div>
#endif
</div>
Try doing this way:
$("#userPost"+id).load(url);
or
$("#userPost"+id).html(data).load(url);

Script to delete Ajax record does not work correctly

I have an Ajax script that should delete entries. It basically works, but when you click the delete button, only the first one is deleted from the list of all records. Although, after reloading the page, the record that disappeared appears and the one I wanted to delete is deleted. How can this be fixed?
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
$("#textpostdata").remove();
},
});
});
});
And html
<div id="textpost">
#foreach($post->comments as $com)
<div id="textpostdata" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
#if(Auth::check())
#if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
#endif
#endif
<hr>
</div>
#endforeach
</div>
you used the same id for multiple elements
the id should be unique, if you use same id for other elements, the html just set that id to first element.
you can use className instead ID like this:
HTML:
<button type="submit" class="btn btn-sm btn-outline-danger py-0 mt-4 delete" data-id="{{ $com->comment_id }}">Удалить</button>
jquery:
$("body").on("click",".delete",function(e){
//other lines of your jquery is ok, because you used $(this) in this line: var id = $(this).data('id');
Jquery - remove the entry after ajax:success
var this_element = $(this); //get the active element, because you can not use $(this) in ajax:sucess!
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
this_element.closest("div").remove(); //remove selected button's whole div!
},
});
NOTE:
when you use className to access the element, you can find the element that event affected on with $(this)
for test use this code: console.log($(this));
Your html is not valid because if there is many comments you have many div with id #textpostdata. You can suffix it with the id of your comment
<div id="textpost">
#foreach($post->comments as $com)
<div id="textpostdata-{{$com->comment_id}}" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
#if(Auth::check())
#if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
#endif
#endif
<hr>
</div>
#endforeach
</div>
Furthermore your query selector should be modified and your delete method should return the deleted element
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (data){
$("#textpostdata" + data.comment_id).remove();
},
});

Using Ajax and Django conditions to display an html variable

I'm new to using Ajax calls with Django. Im trying to implement a simple Display or not display depending on the type of get called by Ajax:
Views:
def dynamic(request):
context = {}
if request.method == 'GET':
if 'backtest_type' in request.GET:
context['display_details'] = False
print ('Im not displaying')
elif 'change_val' in request.GET:
context['display_details'] = True
print ('Im displaying')
else:
context['display_details'] = False
return render(request, "demo/dynamic.html", context)
In my template:
{% extends 'demo/base.html' %}
{% block body %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="{% static 'css/dynamic.css' %}">
<script>
$(document).on('click','#id_backtest_type', function () {
console.log( $(this).val() );
$.ajax({
type: 'get',
data: {'backtest_type': 1},
success: function (data) {
console.log('data sent ' + data);
},
failure: function(data) {
alert('Got an error dude');
}
});
});
$(document).on('click','#btnClick', function () {
// console.log( $(this).val() );
$.ajax({
type: 'get',
data: {'change_val': 1},
success: function (data) {
console.log('data sent ' + data);
failure: function(data) {
alert('Got an error dude');
}
});
});
</script>
<div>
{% if display_details %}
<h1>I'm diplaying</h1>
{% endif %}
</div>
<div id="btnClick" class="col-sm-4">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button class="btn btn-secondary" type="button">Don't Display</button>
</div>
</div>
</div>
<div id="id_backtest_type" class="col-sm-4">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button class="btn btn-secondary" type="button">Display!</button>
</div>
</div>
</div>
{% endblock %}
From the console I'm sure that the get requests are being correctly sent using ajax (the get requests are being sent and the console prints the statements:
[09/Feb/2019 20:00:56] "GET /dynamic/?backtest_type=1 HTTP/1.1" 200
6530
Im displaying
However, even if the ajax call works correctly, the template doesn't end up rendering <h1>I'm diplaying</h1>. Am I misunderstanding anything about Ajax?
Thanks in advance!

Image deleted but page not refreshed ajax laravel

Hi there I am having a problem when I click button delete it deletes the folder with image inside and that is what I want but the page it is not refreshed so I do not know that is deleted till I click refresh
this is the code:
#if($question->question_image)
<img src="{{url('/')}}/images/questions/{{ $question->id }}/medium/{{ $question->question_image }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#else
<img src="{{ asset('noavatars/no-image-selected.png') }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#endif
</div>
{{-- <button type="button" class="btn" id="question_upfile"
style="cursor:pointer; padding-left: 24px; padding-right: 15px;">
<i class="fa fa-upload" aria-hidden="true">
</i>#lang('buttons.upload_image')
</button> --}}
<button type="button" value="{{-- {{ $i }} --}}" class="btn btn-flat btn-default btn-sm delete_image" id="delete_image" title="#lang('buttons.remove_option')"><i class="fa fa-trash-o" aria-hidden="true"></i> </button>
and the javascript code is this:
<script>
$(document).on("click", "button[id=delete_image]", function(data){
var questionid = {{$question->id}};
var element = 'questions';
$.ajax({
type: "POST",
url: "{{ action('website\images\ImagesController#deleteImage') }}",
data: {
_token: "{{ csrf_token() }}",
'id':questionid,
'element' : element,
},
success: function(response) {
console.log(response);
},
error: function(response){
alert("fail");
}
});
function readquestionURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#question_image_box')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
});
</script>
The controller is this:
public function deleteImage($element =null, $id = null){
if(request()->ajax()) {
$id = request()->input('id');
$element = request()->input('element');
if($element != null && $id != null){
Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id);
}
return 1;
}
}
How can I achieve to delete the image and be refreshed at the same time. Can someone please help me thank you very much .
You can refresh the page using javascript
location.reload();
You'll need to add that line on your ajax's success method.

Resources