Kash
Kash

Reputation: 245

Save record on page leave

I am saving records on save button click, if user don't click save button and navigate to another page while clicking on some link even then i want to call the save method. How can I achieve this functionality?

please provide some sample code ...

thanks in advance for your help

Upvotes: 5

Views: 4001

Answers (3)

iJade
iJade

Reputation: 23801

Well since you want to call the save method even if the user navigates to another page or link what u need to do is set a hidden field for eg. suppose hdnSave and set its value to say 0 Now when the user navigates or clicks on any another link first check if this hidden field value(hdnSave) is set to 1 or not.If not then Call Save Method.So this hidden Field can be used as an indicator of whether Save Method has been called or not.

Similarly you can use a session(in c# code) for the same purpose as well.

Upvotes: 1

1000003
1000003

Reputation: 11

Use an ajax post, triggered by window.OnBeforeUnload() to let yourself know that the user has left the page, and pass any information you need.

Upvotes: 1

Wasim Karani
Wasim Karani

Reputation: 8886

You can make ajax request on

window.onbeforeunload = function(){ 
    ////make ajax request
}

Or can prevent the user by giving confirm box

function showalert() {
  if (!confirm('Are you sure you want to exit without saving changes?')) { 
     ////make ajax request
  }
  else {return true;}
}

window.onbeforeunload = function(){ showalert }

For example check this out when I leave this page while answering SO prevent me

enter image description here

Upvotes: 6

Related Questions