jQuery Plugin Autosave EVERY 30 SECONDS

I have found this jQuery Autosave Plugin which works really well.
What I would also like to do is:
- AUTO SAVE EVERY 30 SECONDS (ISH)
- RUN SAVE COMMAND ON BUTTON CLICK

Can anyone help out?? Im very stuck.

My PHP file which saves the data to the database works fine.

MY JAVASCIPT ON TOP OF INDEX.PHP
<script type="text/javascript">
$(function() {
	//Autosave Javascript
	$("input,select,textarea").autosave({
		url: "library/autosave2.php",//set the php file that updates the database
		method: "post",
		dataType: "html",
		grouped: true,//send data for all fields with the autosave
		
		success: function(data) {//on a successful update...
        		//$("#message").html('<img src="../images/small_green_tick.gif" width="20" height="20" /> Data updated successfully').show();//...show a message...
				setTimeout('fadeMessage()',1500);//...and then fade it out after an interval
    		},
		send: function(){//on a save...
        		$("#message").html('<img src="../images/ajax-loader-bar.gif" />').show();//..show a message
				alert ("saving");
			},
		
		error: function(jqXHR, exception) {
			if (jqXHR.status === 0) {
				alert('Not connect.\n Verify Network.');
			} else if (jqXHR.status == 404) {
				alert('Requested page not found. [404]');
			} else if (jqXHR.status == 500) {
				alert('Internal Server Error [500].');
			} else if (exception === 'parsererror') {
				alert('Requested JSON parse failed.');
			} else if (exception === 'timeout') {
				alert('Time out error.');
			} else if (exception === 'abort') {
				alert('Ajax request aborted.');
			} else {
				alert('Uncaught Error.\n' + jqXHR.responseText);
			}
		}
	
	});		
});


function fadeMessage(){
	$('#message').fadeOut('slow');//just a function to fade out the message
}


//Tab Javascript
$('div[data-role="navbar"] a').live('click', function () {
    $(this).addClass('ui-btn-active');
    $('div.content_div').hide();
    $('div#' + $(this).attr('data-href')).show();
});



</script>

Open in new window



JQUERY.AUTOSAVE.JS FILE
/**
 * jQuery Plugin Autosave
 *
 * @author Raymond Julin (raymond[dot]julin[at]gmail[dot]com)
 * @author Mads Erik Forberg (mads[at]hardware[dot]no)
 * @author Simen Graaten (simen[at]hardware[dot]no)
 * amended to cope with jQuery 1.6 or later by Simon Battersby (see http://www.simonbattersby.com/blog/using-the-jquery-autosave-plugin/)
 *
 * Licensed under the MIT License
 *
 * Usage: 
 * $("input.autosave").autosave({ 
 *     url: url, // Defaults to parent form url or window.location.href
 *     method: "post",  // Defaults to parent form url or get
 *     grouped: true, // Defaults to false. States whether all selected fields should be sent in the request or only the one it was triggered upon
 *     success: function(data) { 
 *         console.log(data); 
 *     },
 *     send: function(eventTriggeredByNode) { 
 *         // Do stuff while we wait for the ajax response, defaults to doing nothing
 *         console.log("Saving");
 *     },
 *     error: function(xmlReq, text, errorThrown) { 
 *         // Handler if the ajax request fails, defaults to console.log-ing the ajax request scope
 *         console.log(text);
 *     },
 *     dataType: "json" // Defaults to JSON, but can be XML, HTML and so on
 * });
 *
 * $("form#myForm").autosave(); // Submits entire form each time one of the 
 *                              // elements are changed, except buttons and submits
 *
 *
 * Todo:
 * - Support timed autosave for textareas
 */

(function($) {
		  
	//SB added to cope with jQuery 1.6 or later which requires the use of .prop to correctly post radio buttons 
    if (typeof $.fn.prop !== 'function')
    $.fn.prop = function(name, value){
        if (typeof value === 'undefined') {
            return this.attr(name);
        } else {
            return this.attr(name, value);
        }
    };		  
		  
    $.fn.autosave = function(options) {
        /**
         * Define some needed variables
         * elems is a shortcut for the selected nodes
         * nodes is another shortcut for elems later (wtf)
         * eventName will be used to set what event to connect to
         */
        var elems = $(this), nodes = $(this), eventName;

        options = $.extend({
            grouped: false,
            send: false, // Callback
            error: false, // Callback
            success: false, // Callback
            dataType: "json" // From ajax return point
        }, options);
        
        /**
         * If the root form is used as selector
         * bind to its submit and find all its
         * input fields and bind to them
         */
        if ($(this).is('form')) {
            /* Group all inputelements in this form */
            options.grouped = true;
            elems = nodes = $(this).find(":input,button");
            // Bind to forms submit
            $(this).bind('submit', function(e) {
                e.preventDefault();
                $.fn.autosave._makeRequest(e, nodes, options, $(this));
            });
        }
        /**
         * For each element selected (typically a list of form elements
         * that may, or may not, reside in the same form
         * Build a list of these nodes and bind them to some
         * onchange/onblur events for submitting
         */
        elems.each(function(i) {
            eventName = $(this).is('button,:submit') ? 'click' : 'change';
            $(this).bind(eventName, function (e) {
                eventName == 'click' ? e.preventDefault() : false;
                $.fn.autosave._makeRequest(e, nodes, options, this);
            });
        });
        return $(this);
    }
    
    /**
     * Actually make the http request
     * using previously supplied data
     */
    $.fn.autosave._makeRequest = function(e, nodes, options, actsOn) {
        // Keep variables from global scope
        var vals = {}, form;
        /**
         * Further set default options that require
         * to actually inspect what node autosave was triggered upon
         * Defaults:
         *  -method: post
         *  -url: Will default to parent form if one is found,
         *        if not it will use the current location
         */
        form = $(actsOn).is('form') ? $(actsOn) : $(actsOn.form);
        options = $.extend({
            url: (form.attr('action'))? form.attr('action') : window.location.href,
            method: (form.attr('method')) ? form.attr('method') : "post"
        }, options);

        /**
         * If options.grouped is true we collect every
         * value from every node
         * But if its false we should only push
         * the one element we are acting on
         */
        if (options.grouped) {
            nodes.each(function (i) {
                /**
                 * Do not include button and input:submit as nodes to 
                 * send, EXCEPT if the button/submit was the explicit
                 * target, aka it was clicked
                 */
                if (!$(this).is('button,:submit') || e.currentTarget == this) {
                    if ($(this).is(':radio') && $(this).prop('checked')==false)
                        return;
                    vals[this.name] = $(this).is(':checkbox') ? 
                        $(this).attr('checked') : 
                        $(this).val();
                }
            });
        }
        else {
            vals[actsOn.name] = $(actsOn).is(':checkbox') ? 
                $(actsOn).attr('checked') : 
                $(actsOn).val();
        }
        /**
         * Perform http request and trigger callbacks respectively
         */
        // Callback triggered when ajax sending starts
        options.send ? options.send($(actsOn)) : false;
        $.ajax({
            type: options.method,
            data: vals,
            url: options.url,
            dataType: options.dataType,
            success: function(resp) {
                options.success ? options.success(resp) : false;
            },
            error: function(resp) {
                options.error ? options.error(resp) : false;
            }
        });
    }
})(jQuery);

Open in new window

Steve TinsleyAsked:
Who is Participating?
 
leakim971Connect With a Mentor PluritechnicianCommented:
line 3, replace : //Autosave Javascript
by :
$("#SAVE").click(function() { $("input,select,textarea").trigger("change"); });
setTimeout(function() { $("#SAVE").trigger("click"); }, 30000);

with :
<input type="button" value="SAVE" id="SAVE" />
0
 
Steve TinsleyAuthor Commented:
I forgot to say that when the textfield is clicked off the autosave works OK.
0
 
Steve TinsleyAuthor Commented:
HI leakim971,

Thanks for the pointers...
It kind of works.

First of all I want to get the save button working... So ive only added: $("#SAVE").click(function() { $("input,select,textarea").trigger("change"); });
and the button.

When I click on the button it seems run the script.... 10 TIMES.
Rather than once!
Any ideas??

On the form I have several text boxes annd a few hidden boxes. Im guess its something to do with this but im not sure....

HELP!!!
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
leakim971Connect With a Mentor PluritechnicianCommented:
ok it run one time by fields...
So go for this :
$("#SAVE").click(function() { $(":text:eq(0)").trigger("change"); });
0
 
Steve TinsleyAuthor Commented:
Great! That bit works.

Now I want the autosave to save every 30 seconds as well (starting as soon as the page loads).... Noting to do with the button.

Im guessting I need somehting like this but not really sure:

      setTimeout(function() {
                  $(":text:eq(0)").trigger("change");
            }, 3000);
0
 
leakim971PluritechnicianCommented:
3000 = 3s
else it should work, why not try it?
0
 
Steve TinsleyAuthor Commented:
Watching firebug and it doesn't do it...
Is it something to do with the plugin and when the text-field looses focus????

Ideally I want it to auto save without leaving the texbox. The curser may be in the textbox of 5 minutes.
0
 
leakim971PluritechnicianCommented:
no error in your page?
0
 
Steve TinsleyAuthor Commented:
nothing
0
 
leakim971PluritechnicianCommented:
do ou get the alert with:
setTimeout(function() {
alert("ok");
                  $(":text:eq(0)").trigger("change");
            }, 3000);

Open in new window

0
 
Steve TinsleyAuthor Commented:
I have managed to VPN into the office and test....

I added:
      setTimeout(function() {
                  alert ("test");
                  $(":text:eq(0)").trigger("change");
            }, 3000);

and when I open the page i get alert test ONCE
and no form post.

Ahhhh!!!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.