jQuery Still Submits Ajax Post Even When “Cancel” is clicked on Confirm Dialog

谁说胖子不能爱 提交于 2019-12-24 22:03:07

问题


I have the following script I use for deleting users. The script works if I confirm that I want to delete the user but if I choose to cancel, the script still processes the ajax submission and deletes the user. I thought by setting an empty else{} statement would act as "do nothing" but apparently I was wrong there.

        $("#user_delete_submit").click(function(){
        var dataString = $("#frm_user_delete").serialize();
        if(confirm("This cannot be undone, are you sure?")){
            $.ajax({
                type: "POST",
                url: "/admin/user_delete.php",
                data: dataString,
                dataType : "json"
            })
            .done(function (data) {
                $("#user_delete_dialog").dialog({
                    autoOpen: false,
                    modal: true,
                    close: function(event, ui) { window.location.href = "/admin/user_list.php"; },
                    title: "Account Deletion",
                    resizable: false,
                    width: 500,
                    height: "auto"
                });
                $("#user_delete_dialog").html(data.message);
                $("#user_delete_dialog").dialog("open");
            });
            return false; // required to block normal submit since you used ajax
        }else{
        }
    });

回答1:


in else return false like this:

$("#user_delete_submit").click(function(){
    var dataString = $("#frm_user_delete").serialize();
    if(confirm("This cannot be undone, are you sure?")){
        $.ajax({
            type: "POST",
            url: "/admin/user_delete.php",
            data: dataString,
            dataType : "json"
        })
        .done(function (data) {
            $("#user_delete_dialog").dialog({
                autoOpen: false,
                modal: true,
                close: function(event, ui) { window.location.href = "/admin/user_list.php"; },
                title: "Account Deletion",
                resizable: false,
                width: 500,
                height: "auto"
            });
            $("#user_delete_dialog").html(data.message);
            $("#user_delete_dialog").dialog("open");
        });
        return false; // required to block normal submit since you used ajax
    }else{
       return false;
    }
});


来源:https://stackoverflow.com/questions/23051989/jquery-still-submits-ajax-post-even-when-cancel-is-clicked-on-confirm-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!