JSFiddle - React, Tailwind, and code Playground
HTML
<form id="the-form" method="post" action="/echo/html/">
<input type="text" name="foo" />
<input type="submit" />
</form>
JavaScript
jQuery.fn.ajaxify = function (selector, success, error) {
// Handle the optional case of selector.
if (arguments.length === 2) {
error = success;
success = selector;
selector = undefined;
}
return this.on('submit', function (e) {
// Copy the options from the '<form />' control.
jQuery.ajax({
url: this.target,
method: this.method || 'GET',
data: (typeof selector === 'undefined' ? $(this).serialize() : $(this).find(selector).serialize())
}).done(jQuery.proxy(success, this)).fail(jQuery.proxy(error, this));
e.preventDefault(); // Don't forget to stop the form from being submitted the "normal" way.
});
};
jQuery(document).ready(function ($) {
$('#the-form').ajaxify(function (response) {
alert('Success!');
}, function (xhr, error) {
alert('Whoops...');
})
});