Reputation: 3368
js and ajax call to delete the record:
$('.delete').click(function (e) {
if (confirm("Are you sure want to delete record?")) {
return true;
}
else {
e.preventDefault();
}
});
$('.type_delete').click(function() {
var csrf_token = $("#csrf_token").val();
var id = $(this).attr('id');
$.ajax({ // create an AJAX call...
data:{
csrfmiddlewaretoken: ('{{csrf_token}}'),
delete:id
},
type:'POST',
url: '/setting/type/', // the file to call
cache:false,
success: function() { // on success..
window.location.href = window.location;
}
});
return false;
});
});
views.py
def types(request):
if request.method == 'POST':
if 'delete' in request.POST:
Types.objects.filter(id=request.POST['delete']).delete()
"""""""""
return render
html:
<input type="button" name="delete" value="Delete" id="{{ type.id }}" class="type_delete delete"/>
The above ajax is to fetch the correct id from html and delete that particular data.Delete is working fine,i am using the delete confirmation dialog box,the problem is the data gets delete even if i press cancel button or close symbol.It should happen only if i press ok.I need help to solve this problem.
Upvotes: 0
Views: 1698
Reputation: 5126
By the time your confirmation box is displayed, the call to second function is already underway. You need to define the second function as another independent function and then call it from within first one.
Here is an example:
$('.delete').click(function (e) {
e.preventDefault();
if (confirm("Are you sure want to delete record?")) {
doDelete($(this).attr('id'))
}
});
function doDelete(elemId) {
var csrf_token = $("#csrf_token").val();
var id = elemId;
$.ajax({ // create an AJAX call...
data:{
csrfmiddlewaretoken: ('{{csrf_token}}'),
delete:id
},
type:'POST',
url: '/setting/type/', // the file to call
cache:false,
success: function() { // on success..
window.location.href = window.location;
});
}
Upvotes: 1
Reputation: 318182
The condition in one event handler doesn't necessarily work in the second event handler, you have to join it all in one event handler :
$('.type_delete').on('click', function (e) {
e.preventDefault();
if (confirm("Are you sure want to delete record?")) {
var csrf_token = $("#csrf_token").val(),
id = this.id;
$.ajax({
data: {
csrfmiddlewaretoken: '{{'+csrf_token+'}}',
delete: id
},
type: 'POST',
url: '/setting/type/',
cache: false
});
}
});
Upvotes: 0