Skip to content

Instantly share code, notes, and snippets.

@miguelperez
Created January 12, 2013 18:41
Show Gist options
  • Save miguelperez/4519857 to your computer and use it in GitHub Desktop.
Save miguelperez/4519857 to your computer and use it in GitHub Desktop.
Whenever you want to send a form as ajax, include this small snipet of code for that...
// Receives the selector of a form and return the params as an array
// Example:
// ["date=2013-01-11", "transactions[][transaction_type]=withdrawal", "transactions[][ammount]=", "transactions[][description]="]
function formAsParams(formSelector){
var array = $(formSelector).serializeArray(),
params = _.reduce(array, function(memo, elem){ memo.push(elem.name + "=" + elem.value); return memo; }, []);
return params;
}
// Given a form with data-attributes data-post-to and data-method, it will do an ajax request to the url
// given in data-post-to using the html method provided in data-method.
//
// This function is useful when you want to submit a form (without files) as an ajax request using jquery AJAX.
//
// Example call:
//
// formToJson({
// formSelector: '#my-form-id',
// successCallback: function(){console.log('Success')},
// beforeCallback: function(){console.log('before')},
// errorCallback: function(){console.log('error')},
// completeCallback: function(){console.log('completed')}
// });
function formToJson(attributes){
var
options = $.extend({formSelector: null, successCallback: null, beforeCallback: null, errorCallback:null, completeCallback: null}, attributes),
form = $(options.formSelector),
ajaxPath = form.attr('data-post-to'),
method = form.attr('data-method');
form.on('submit', function(evt){
evt.stopPropagation();
evt.preventDefault();
$.ajax(ajaxPath, {
dataType: 'json',
type: method,
data: formAsParams(options.formSelector).join("&"),
beforeSend: function(data){
if(options.beforeCallback) {
options.beforeCallback(data);
}
},
success: function(data){
if(options.successCallback) {
options.successCallback(data);
}
},
error: function(data){
if(options.errorCallback) {
options.errorCallback(data);
}
},
complete: function(data){
if(options.completeCallback) {
options.completeCallback(data);
}
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment