codeninja codeninja - 7 days ago 5
Javascript Question

press confirm button before save

I'm having a problem with the way I save information in ajax with alert, I made it using confirm in JQuery but the button text can't be changed I so decided to make my own dialog box so I can modify the buttons, but the problem is the data saves before I click the save button.

function saveEdit(e) {
var result = '';
var item = $('input[name=username]').val();
$.ajax({
url: root + 'ccards/getAllDetails',
data: {
item: item
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var hour = dateObj.getUTCHours()
var minute = dateObj.getUTCMinutes();
var second = dateObj.getUTCSeconds();

var datetoday = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;

var selected_date = Date.parse(data.modified);
var today = Date.parse(datetoday);

var d = new Date(data.modified);
var h = d.getHours();
var m = d.getMinutes();

var username = data.username.toUpperCase();
var coreuser = data.core_user.username.toUpperCase();
var hr = '';
var time = '';

if (h <= '12') {
hr = h;
time = hr + ":" + m + " AM";
} else {
hr = h - 12;
time = hr + ":" + m + " PM";
}

if (Math.abs(today - selected_date) <= 60 * 60 * 24 * 1000) {

$('#confirmSave').show().dialog({
height: 200,
width: 500,
zIndex: 10,
modal: true,
resizable: false
});

$('#time').html(time);
$('#coreuser').html(coreuser);

if ($('#confirmSave button[name=submit]').data('clicked')) {
result = true;


} else if ($('#confirmSave button[name=cancel]').data('clicked')) {
result = false;
}
}
}
});

return result;
}

$('.clientForm').submit(function(event) {

var form = this;
console.log(form);
if ($("input[name='action']", form).val() == 'save' || $("input[name='action']", form).val() == 'savenew' || $("input[name='action']", form).val() == 'login') {
if ((!validate_email(form)) || (!validate(form))) {
mode = 'edit';
setMode(mode);
return false;
}
}

var save = saveEdit();
if (save == true) {

var dt = $(this).serializeArray();

var action = root + $("input[name='module']", form).val() + $("input[name='method']", form).val();
$('.fields', this).slideUp('fast');
$('.response', this).html("<div class='load'>Processing, please wait...</div>");
$.ajax({
type: 'POST',
url: action,
data: dt,
dataType: 'json',
success: function(data) {
if (data) procJSON.init(data, form);

},
complete: function(data) {

},
error: function(data) {
onError(data);
}
});
}
return false;
});

Answer

I recently used the noty plugin, alongside jQuery's deferred to solve a similar problem.

First, a function to show the confirm dialog and return a promise-like object, which resolves to true if the Ok button is pressed, or false if the Cancel button is pressed.

function showConfirm(msg) {
    var dfd = $.Deferred();
    noty({
        text: msg,
        type: 'confirm',
        dismissQueue: false,
        layout: 'center',
        theme: 'defaultTheme',
        modal: true,
        buttons:
        [{
            addClass: 'btn btn-primary', 
            text: 'Ok', 
            onClick: $noty => {
                $noty.close();
                dfd.resolve(true);
            }
        },
        {
            addClass: 'btn btn-danger', 
            text: 'Cancel', 
            onClick: $noty => {
                $noty.close();
                dfd.resolve(false);
            }
        }]
   });    
return dfd.promise();
}

Then you can do something like...

$('.clientForm').submit(function(event) {
    showConfirm("Do you wish to save?").then(function(confirmed) {
        if (!confirmed) {
            return;
        }
        // make ajax request here
    }
}