Skip to content

Instantly share code, notes, and snippets.

Created April 9, 2014 17:41
Show Gist options
  • Save anonymous/10295917 to your computer and use it in GitHub Desktop.
Save anonymous/10295917 to your computer and use it in GitHub Desktop.
Example of a jQuery form submission
$('form').on('submit', function(e){
// Keeps the form from refreshing the page
e.preventDefault();
// Cached reference to the form (the less lookups the better)
var self = $(this);
// Combs through the form and converts all the inputs into serialized versions to be
// interpreted by wherever you are sending the data
// https://api.jquery.com/serialize/
var collectedData = self.serialize();
// Ship your form data back to the same page via a POST request
// You can change the destination to whatever you want, e.g. '/schedule/save' instead of window.location.href
// https://api.jquery.com/jQuery.post/
var request = $.post( window.location.href, collectedData );
request.done(function(){
// Server said everything was okay! Show a success message or something.
self.find('.success').show();
});
request.fail(function(){
// Server sent back a 4xx or 5xx error code, meaning something broke or was wrong. Boooo.
self.find('.error').show();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment