Search code examples
jqueryajaxjquery-ui-dialogconfirm

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


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{
        }
    });

Solution

  • 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;
        }
    });