-1

I'm making a webpage and I need to update a database in a Node.js server when the window is closed.

The code is:

window.close(function(){
event.preventDefault();
var UrlCierra = location.search && location.search.split('=')[1];
var cierro = $.post( '/updatesala/cerrarventana', {url: UrlCierra} );  
    cierro.done(function(data){
        if (data=="Cierra"){
            window.close();
            }
            });
});

I know that the code is wrong, but how can I fix it?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Gie-Sakura
  • 117
  • 2
  • 10
  • Doesn't really make sense needing to send that data when it was already processed by server when page was loaded. What is purpose of parsing the url just before window closes? – charlietfl Jan 19 '16 at 01:45
  • `navigator.sendBeacon` works in good browsers (in other words **NOT** internet explorer or safari) - use the onbeforeunlaod with async false **kludge** for the stupid browsers and `navigator.sendBeacon` for browsers you'd bring home to your parents – Jaromanda X Jan 19 '16 at 01:49

2 Answers2

0

As explained in another answer, doing so is probably a very bad idea because:

  1. The request may not complete before the page is unloaded, and
  2. Forcing a synchronous request will cause the page unload to block until the request completes, which is an awful user experience.

It looks like you're trying to make sure something gets updated even if someone quits the page early in the workflow?

Revisit the workflow and see if there isn't a more elegant (and safer) solution, like saving when the input's blur event fires, for example.

Community
  • 1
  • 1
msanford
  • 11,803
  • 11
  • 66
  • 93
-1

You can use unbeforeunload event.

window.addEventListener('onbeforeunload', () => {
    // sync call here
});

If you need an ajax call, make sure to use synchronous (async:false in jQuery) call. Which is deprecated, and Chrome will ignore if it's not completed in one second.

Fella
  • 124
  • 5