jQuery ajax not working with JS confirmation modal
When a user clicks on Delete this post a modal pops up asking if the user is sure.
If OK, the AJAX proceeds as normal. But if the user clicks on Cancel, the delete action is happening as well.
I've tried return false
in several parts of this AJAX code but it completely blocks the AJAX request.
I'd like to accomplish the correct behavior without using additional plugins (ie, dialog) -- anyone have suggestions? Thanks!
AJAX
$('.posts_delete').live('click', function(e){
e.preventDefault();
var id = $(this).attr('id');
var last_seg = id.substr(id.lastIndexOf('_') + 1);
var link = 'chat/posts_delete/' + last_seg;
$.ajax({
url: link,
dataType: "html",
beforeSend: function(){
confirmDeletePost();
// return false;
},
success: function() {
$('#chat_thread').load('chat/posts_ajax/<?php echo $page_id; ?>');
$('#posts_form input').val('');
}
});
});
J开发者_运维技巧S
function confirmDeletePost() {
return confirm("This post will be removed and you can't undo this action. Are you sure you want to delete?");
}
check this http://jsfiddle.net/jansian/wupmq/
Hope it helps. :)
You need to return the result of the confirm
— return false
if the user cancels.
It would be simpler to use an if
to only send the request if the user clicks OK in the first place.
This should work (attention! not tested):
$('.posts_delete').live('click', function(e){
e.preventDefault();
if (confirm("This post will be removed and you can't undo this action. Are you sure you want to delete?")){
var id = $(this).attr('id');
var last_seg = id.substr(id.lastIndexOf('_') + 1);
var link = 'chat/posts_delete/' + last_seg;
$.ajax({
url: link,
dataType: "html",
beforeSend: function(){
confirmDeletePost();
// return false;
},
success: function() {
$('#chat_thread').load('chat/posts_ajax/<?php echo $page_id; ?>');
$('#posts_form input').val('');
}
});
}
});
精彩评论