-1

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;
});
empiric
  • 7,825
  • 7
  • 37
  • 48
codeninja
  • 98
  • 1
  • 1
  • 11
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – André Dion Nov 30 '16 at 16:54
  • 1
    If I see that correct you are showing the confirmation in the `success` function, of course than the data is already saved. Just show the dialog and invoke the `ajax` call only if the right button is saved – empiric Nov 30 '16 at 16:56
  • For future question please have a look at how to set up a [minimal example](http://stackoverflow.com/help/mcve) whihc only contains the relevant code to your specific problem – empiric Nov 30 '16 at 16:58
  • 1 show dialog, 2 continue with code while dialog is being shown 3 return result 4 user (later) clicks dialog 5 set value of result. – freedomn-m Nov 30 '16 at 17:17

1 Answers1

0

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
    }
}
Alex Young
  • 4,009
  • 1
  • 16
  • 34
  • just have to ask this, is there any other way to solve this problem without noty plugin? – codeninja Nov 30 '16 at 18:14
  • There are loads of ways you could achieve this, the simplest would just be to use native javascript's confirm method. – Alex Young Nov 30 '16 at 19:59
  • The reason I did not use the native javascript's confirm method was because the buttons text can't be modified or changed. – codeninja Dec 06 '16 at 21:12