better software through user-centered design

jQuery Form Post

This is a wrapper for submitting forms. I use this with ASP.Net MVC and specifically with MVC3 because the serialized data will automatically bind to the model.
Post Dependencies: JSON2.js by Douglas Crockford, Serialize Function by me, Ajax Wrapper by me

/// Posts existing form via ajax. Automagically binds your form elements to the view model.
Post: function (options) {

var defaults = {

onSubmit: null, /// function to run before default validation occurs (used for custom validation)
onAjaxSuccess: null, /// function to run when ajax returns successful
onAjaxComplete: null, /// function to run on ajax completion
onAjaxError: null, /// function to run when ajax returns error
targetId: '' /// id of the element to dump the results in

}, json = {}, formObject = $(this);

this.submit(function (event) {

try {
/// Prevent form from submitting
event.preventDefault();

/// Use the OnSubmit even to run any custom validations you may have.
if (options.onSubmit) {
var onSubmitResult = options.onSubmit.apply(this, Array.prototype.slice.call(arguments));
if (onSubmitResult !== undefined && onSubmitResult === false) {
return onSubmitResult;
}
}

/// Check if form is valid and stop submit if it is not.
if (!$(this).valid()) { return false; }

if (options.targetId && !$("#" + options.targetId).is(":empty")) {
$("#" + options.targetId).empty();
}

/// Serialize form elements and associated data options
json = formObject.Form('Serialize', options);

MyNamespace.Ajax.Post({
url: formObject.attr('action'),
type: formObject.attr('method'),
dataType: 'html',
data: JSON.stringify(json),
success: function (result) {
try {
if (options.onAjaxSuccess) {
options.onAjaxSuccess.apply(this, Array.prototype.slice.call(arguments));
}
} catch (error) {
MyNamespace.Utilities.LogError(error);
}
},
complete: function (XMLHttpRequest, textStatus) {
try {
if (options.onAjaxComplete) {
options.onAjaxComplete.apply(this, Array.prototype.slice.call(arguments));
}
} catch (error) {
MyNamespace.Utilities.LogError(error);
}
},
error: function(error){
MyNamespace.Utilities.LogError(error);
try {
if (options.onAjaxError) {
options.onAjaxError.apply(this, Array.prototype.slice.call(arguments));
}
} catch(error){
MyNamespace.Utilities.LogError(error);
}
}
});

} catch (error) {
MyNamespace.Utilities.LogError(error);
}

});
return this;

} //end Post

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: