Updating your forms without pressing submit - an example

This is an example that goes with the article on the RGraph blog that details how to update your forms without having to press a submit button. It shows a message to the user when the details have been saved so that they are made aware of this.

« Back to the article

This is the JavaScript AJAX code that saves the form when a key is pressed. It passes the form values by an AJAX request to the server which can then save the values.
    TIMERS = {};

    // Save the information from the form by sending to the server via an
    // AJAX GET request
    function saveformdata()
        var opt = {
            name: document.getElementById('name').value,
            age: document.getElementById('age').value,
            location: document.getElementById('location').value

        if (TIMERS.SAVEDATA) {

        TIMERS.SAVEDATA = setTimeout(function ()
            var url;

            // Trigger the AJAX GET request that gives the information
            // to the server
                url = '/blog/how-to-use-ajax-to-update-forms-without-pressing-submit-example.html?'
                    + '&name='     + encodeURIComponent(opt.name)
                    + '&age='      + encodeURIComponent(opt.age)
                    + '&location=' + encodeURIComponent(opt.location)

            // Note that it has been saved
                .text('Information has been saved')
                    opacity: 1

            // Fade out the message after 5 seconds
            setTimeout(function ()
                    opacity: 0
                }, 250);
            }, 5000);

            TIMERS.SAVEDATA = null;
        }, 1000);