I have made a form in drupal.

What I want is when the browser unload the page from any click whether by clicking on anchor tag or from browser refresh buttons I want to save data of my form through js/ajax or anything possible in drupal.

If any more explanation needed please do ask me. Thanks in advance.

I was trying do this by browser 'unload' event and 'beforeunload' event. But unable to save data of my form because browser doesn't wait for anything writtent inside and just ask for confirmation. Any help will appreciated.

This what I was trying to do:

$(window).bind('beforeunload', function() {
  return 'Do you really want to leave?';
  //coming here instead of it what i want
  //is save the form then return if user says yes and no the don't save the form.

2 Answers 2


You would need to create your own AJAX implementation to achieve this. Upon some trigger, whenever you want that to be, (I would make it save any time a field looses focus), you would perform an AJAX call saving the information into a database. When the user returns, provided they are traceable in some way either through their UID or a valid session, you would fill the form out again with the information from the temporary table in the database. When the user completes the form, let Drupal write the data accordingly. Otherwise, there is no way to save the users information and present it to them again. This method, if the user is registered, would always work. Make sure you add a "clear form" button though so they can clear it if they want.

Update: You could use .unload

  • Can we do it by any event from the browser and save it when browser about to unload the page? Thanks
    – Pradeep
    Commented Jan 17, 2014 at 5:59
  • Updated my answer. Commented Jan 17, 2014 at 15:37
  • I read about the .unload but it I need to show confirmation and if user cancel then prevent the default action. But in case of unload we cannot do that. And also unload is not working I tried with beforeunload. But it's result is different in different browser. And also I need to theme a confirm box.
    – Pradeep
    Commented Feb 3, 2014 at 6:23
  • It is considered very bad practice to stop a user from closing a browser. And yes, it doesn't work the same in all browsers. I would highly recommend you take my suggestion and program the form to save every field on exit. This way, it doesn't matter what the user does or what browser they have. Commented Feb 3, 2014 at 15:32

I have implemented above on anchor with ajax. (i.e.) I have checked if a form is edited then a alert is shown if user clicks on any anchor element. Afterwards user form is saved if user agrees else changes discarded. For browser refresh, I didn't get any solution. Thanks for this help and discussion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.