2

E.g. someone is writing an article but accidently closes the browser. Is it possible to save everything he wrote?

Something like this:

onExit -> get all the information the user filled -> AJAX request that saves the information in a database.

Or

is it only possible by preemptively saving every x second?

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
guy1997
  • 156
  • 2
  • 14
  • There is the "beforeunload" event. I'm not sure if an Ajax request would work. If not, try storing the data in `localStorage`... – Šime Vidas Jun 04 '12 at 13:19
  • You're looking for the [`onunload`](https://developer.mozilla.org/en/DOM/window.onunload) event. – Snuffleupagus Jun 04 '12 at 13:19
  • Some StackOverflow topics are already on the same subject. See [here](http://stackoverflow.com/questions/5310392/onbeforeunload-wait-for-ajax-result), [here](http://stackoverflow.com/questions/10300250/ajax-and-onbeforeunload-event) and [here](http://stackoverflow.com/questions/1244535/alert-when-browser-window-closed-accidentally). – Val Jun 04 '12 at 13:23

3 Answers3

2

My company does this by running an ajax query to save every 5 seconds, but you should look into localStorage for saving on the client, use onunload to save to that and recover it later.

I made a html5 notepad that stores to localStorage every onchange event and every 500ms and onbeforeunload to save one field, but it is easy to modify, here's the (essential) code:

<textarea placeholder="Type here, see it here..."  id="notepad"></textarea>
<script>
    var n = document.getElementById("notepad");
    /* save */
    var s = function(){localStorage.setItem("notepad", n.value);}
    /* retrieve (only on page load) */
    if(window.localStorage){ n.value = localStorage.getItem("notepad");}
    /* autosave onchange and every 500ms and when you close the window */
    n.onchange = s();
    setInterval( s, 500);
    window.onunload = s();
</script>

if you view source on that page, you'll also find a polyfill used to support older browsers, but localStorage should work in IE8+

I wouldn't trust the client to complete an ajax call in the onbeforeunload alone, but I really don't everything about how that function works in the top browsers.

JKirchartz
  • 17,612
  • 7
  • 60
  • 88
  • 1
    @Valentin that's what [polyfills](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills) are for – JKirchartz Jun 04 '12 at 13:30
1

I would likely use a combination of local storage and ajax, and i would use a delayed setTimeout such that the ajax request is made after a period of inactivity.

So for example you would bind your ajax refresh to the events of the items you want saved:

$("#fieldToSave").bind("keyup",(function()
        {
            var timeoutId = null;
            var previous = "";
            return function(e)
            {
                var that = this;

                if ($(that).val() != previous)
                {
                    previous = $(that).val();
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(function()
                    {
                        ajaxRefresh();

                        if(window.localStorage)
                        {
                            localStorage.setItem("notepad", that.value);} 
                        }
                    }, 300);
                }
            };
        })());

This approach persists the value of "fieldToSave" using both ajax and local storage, additionally it doesn't continually save over and over. What it does is on keyup for example, it will perform the save but only once every 300 milliseconds. So if a user is typing continually it won't save until the user stops for 300 milliseconds. This can really be bound to any event you want.

How/where you decide to load the content from when the page loads is for you to decide.

Hope this helps.

Mark At Ramp51
  • 5,343
  • 1
  • 25
  • 30
0

Answer of : iss it only possible by preemptively saving every x second? is below

You need to call ajax function certain amout of time as i done in blelow code...settime out function call the ajaxRefresh function after every 1000 seconds...

function onLoad() {
    setTimeout(ajaxRefresh, 1000);
} 

function ajaxRefresh()
{
    //ajax code to post data 
    $.ajax({
                type: "GET",        //GET or POST or PUT or DELETE verb
                url: ajaxUrl,       // Location of the service
                data: "",       //Data sent to server
                contentType: "",        // content type sent to server
                dataType: "json",   //Expected data format from server
                processdata: true,  //True or False
                success: function (json) {//On Successful service call
                    var result = json.name;
                    $("#dvAjax").html(result);
                },
                error: function() { alert("err")};  // When Service call fails
            });

    setTimeout(ajaxRefresh, 1000);
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263