0

I have a settings page with a form. I noticed that people often forget to click the save button, so I decided to send a POST request with $.ajax() on window.onbeforeunload. I'd also like a loader (from Semantic UI) to show before sending the request and hide when it is completed.

This is what I have:

function save(e) {
  var msg = 'Your settings were not saved. Please do not leave yet so we can try saving again';
  $('form').dimmer('show');

  var xhr = $.ajax('settings.php', {type: "POST", 
    data: $('form').serialize(), async: false});

  $('form').dimmer('hide');

  if (xhr.status !== 200){
    $('form').submit(); //will trigger if the user stays
    if (e)
      return e.returnValue = msg;
  }
}

if ('onbeforeunload' in window)
  window.onbeforeunload = save;
else if ('onunload' in window)
  window.onunload = save;
else {
  var button = $('noscript.submitParent').text();
  $('.ui.form.segment').append(button);
}

But now, the loader won't show up until the request is done. I suspect this happens because of async: false, which is necessary so that the page does not unload.

Any suggestions on how to show the loader before sending the request? Is it possible?
I tried $(window).trigger('resize') from here and $('form .dimmer').height() (idea from here), didn't work.

I'm aware of the localStorage alternative, but I'd like not to use it if possible.

I use jQuery 2.1.1

Community
  • 1
  • 1
anestv
  • 543
  • 6
  • 28

0 Answers0