Solved

jQuery Plugin Autosave EVERY 30 SECONDS

Posted on 2013-01-10
11
1,473 Views
Last Modified: 2013-02-12
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

0
Comment
Question by:sjtinsley83
  • 6
  • 5
11 Comments
 

Author Comment

by:sjtinsley83
ID: 38763053
I forgot to say that when the textfield is clicked off the autosave works OK.
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 38763201
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
 

Author Comment

by:sjtinsley83
ID: 38763283
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
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 500 total points
ID: 38763441
ok it run one time by fields...
So go for this :
$("#SAVE").click(function() { $(":text:eq(0)").trigger("change"); });
0
 

Author Comment

by:sjtinsley83
ID: 38763547
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 82

Expert Comment

by:leakim971
ID: 38763557
3000 = 3s
else it should work, why not try it?
0
 

Author Comment

by:sjtinsley83
ID: 38763691
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
 
LVL 82

Expert Comment

by:leakim971
ID: 38763738
no error in your page?
0
 

Author Comment

by:sjtinsley83
ID: 38763911
nothing
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38763961
do ou get the alert with:
setTimeout(function() {
alert("ok");
                  $(":text:eq(0)").trigger("change");
            }, 3000);

Open in new window

0
 

Author Comment

by:sjtinsley83
ID: 38764594
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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now