views:

1427

answers:

3

In the window.onbeforeunload event is there a way to detect if the new request is a POST(on the same page) or a GET(going to a page)? It would also be great to see the new document.location.

window.onbeforeunload = winClose;
function winClose() {
    //Need a way to detect if it is a POST or GET
    if (needToConfirm) {       
        return "You have made changes. Are you sure you want?";
    }
}
A: 

Sounds like something you'd need to attach to a form, or specific links. If the event is raised by a link, and there is a request string full of variables, it will act as a GET. If it's a form, you'll have to check the METHOD, and then figure the URL based on the data being submitted in the form itself.

<a href="thisPage.php">No method</a>
<a href="thisPage.php?usrName=jonathan">GET method</a>
<form method="GET" action="thisPage.php">
  <!-- This is a GET, according to the method -->
  <input type="text" name="usrName" value="jonathan" />
</form>
<form method="POST" action="thisPage.php">
  <!-- This is a POST, according to the method -->
  <input type="text" name="usrName" value="jonathan" />
</form>

So the detection would take place not in the window method, but in the click method of your links, and form submissions.

/* Check method of form */
$("form").submit(function(){
  var method = $(this).attr("method");
  alert(method);
});

/* Check method of links...UNTESTED */
$("a.checkMethod").click(function(){
  var isGet = $(this).attr("href").get(0).indexOf("?");
  alert(isGet);
});
Jonathan Sampson
Yeah I am wondering how I check the method from the javascript?eg something like this.. eg window.Method == "POST"
James_Dude
+3  A: 

This is how I just did it:

$(document).ready(function(){
  var action_is_post = false;
  $("form").submit(function () {
    action_is_post = true;
  });

  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    if (!action_is_post)
      return 'You are trying to leave this page without saving the data back to the server.';
  }
});
markwatson
Thanks, this is exactly what I was looking for!
Coderuckus
A: 

@markwatson - lifesaver +1

Dirty Bird Design

related questions