Created
April 1, 2015 11:41
-
-
Save martinbean/a1b763088b861bb75179 to your computer and use it in GitHub Desktop.
jQuery AJAX submit plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Submit a form via AJAX and return the request object | |
$.fn.ajaxSubmit = function (options) { | |
var settings = $.extend({ | |
submittingText: 'Submitting...' | |
}, options); | |
var form = $(this); | |
var url = form.attr('action'); | |
var data = form.serialize(); | |
var type = form.attr('method'); | |
var submitButton = form.find('[type="submit"]'); | |
var originalSubmitButtonText = submitButton.text(); | |
var request = $.ajax({ | |
data: data, | |
dataType: 'json', | |
type: type, | |
url: url | |
}); | |
submitButton.prop('disabled', true).text(settings.submittingText); | |
request.always(function () { | |
submitButton.prop('disabled', false); | |
submitButton.text(originalSubmitButtonText); | |
}); | |
return request; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = $('form').ajaxSubmit({ | |
submittingText: 'Adding Record...' | |
}); | |
request.done(function (response) { | |
// POST was successful | |
}); | |
request.fail(function (jqXHR, textStatus, errorThrown) { | |
// POST failed | |
// JSON can be found in jqXHR.responseJSON | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment