I have a function that I pass a form
element into in order to handle form submits using AJAX.
I want to return the ajax object that will be handling the form submit from my function so that I can attach additional done
callbacks -- the problem is I don't know how to return the ajax object without creating it(and executing it) first.
How can I substitute a promise in lieu of the actual ajax object so that I return something to attach extra callbacks to?
HandleModalFormSubmit: function (element) {
var form,
modalcontainer = $(element).closest('.modal'),
modal = $(element).closest('.modal-dialog'),
ajaxdata;
if (element.is('form')) form = $(element);
else {
form = element.find('form');
}
$.validator.unobtrusive.parse(form);
$(element).on('submit', function (event) {
event.preventDefault();
ajaxdata = $.ajax({
type: form.method,
url: form.action,
data: $(form).serialize()
}).done(function (data) {
if (data.status == null) {
modal.html(data);
} else {
modalcontainer.modal('hide');
};
}).always(function (data) {
modal.spin(false);
modal.fadeTo(500, 1);
});
modal.fadeTo(300, 0);
modal.spin();
});
var returningobject = {
element: form,
ajax: ajaxdata
};
return returningobject;
}
}
EDIT: Here is what I'd like to have happen with the function
var formobject = $Global.HandleAjaxForm(element);
formobject.ajax.done(function(data1) {
if (data1.status == 'ok')
window.location.href = (data.redirectToUrl == null) ? "~/Dashboard" : data.redirectToUrl;
});