Javascript auto-submit form

I was working on this for a new site idea (not for this one, it’s be a whole new site) and made this, it’ll defiantly come in useful to me later, probably to others too. What this little function does is submit the data using ajax whenever the as() function is called. This can be used in a few ways, the two more obvious, and probably most useful, ones are having a form submit button ass the as() function to submit the data without having to reload or redirect the user, the other is the method I’m using.

I’m using this to automatically submit the form whenever it is updated, so i’ve placed in on the forms keyup event. That way, when something is typed in any part of the form it’s sent to the server for an update. When using this method you’ll want to make sure your save code is very lightweight (I suggest checking the form contents meet any requirements before sending it and having the form just update the data near blindly (better run a check for injection hacks but thats it), and of couse not doing that on anything where data loss is going to cause headaches). Anyways enough babble, here’s the code


Things to note about the code. I set the first variable sent manually (on line 3) if you don’t want one set by the script then you can remove that line but you’ll have to remove the first “&” or you’ll get some unexpected events (probably, I wouldn’t try it). If you want to use a GET instead of the POST then you’ll have to re-jigger a bit, I can do if for you if you want just leave a comment. Also, as with a lot of my stuff, no IE to test on. Should work though (I’ve made sure not to repeat thing I know don’t work in IE), if someone tries it and it fails let me know (and with what error) and I’ll fix it.

Update: 11/24/10 1:51am
Removed an alert that did nothing but annoy, changed the line reference accordingly.

Update 12/29/10 11:10pm
Added a example of this in action to the example page. It’s a pretty simple example but shows it working, I can always come up with a better one if it’s not clear enough or if it’s not useful for a particular application your trying.

One Reply to “Javascript auto-submit form”

Leave a Reply

Your email address will not be published. Required fields are marked *