Created
February 10, 2013 02:02
-
-
Save HarrisonJackson/4747987 to your computer and use it in GitHub Desktop.
Jquery 1.8+ ajax submit - with new callbacks
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
// variable to hold request | |
var request; | |
// bind to the submit event of our form | |
$("#myform").submit(function(event){ | |
// abort any pending request | |
if (request) { | |
request.abort(); | |
} | |
// setup some local variables | |
var $form = $(this); | |
// let's select and cache all the fields | |
var $inputs = $form.find("input, select, button, textarea"); | |
// serialize the data in the form | |
var serializedData = $form.serialize(); | |
// disable the inputs for the duration of the ajax request | |
$inputs.prop("disabled", true); | |
// fire off the request to /form.php | |
var request = $.ajax({ | |
url: "/form.php", | |
type: "post", | |
data: serializedData | |
}); | |
// callback handler that will be called on success | |
request.done(function (response, textStatus, jqXHR){ | |
// log a message to the console | |
console.log("Hooray, it worked!"); | |
}); | |
// callback handler that will be called on failure | |
request.fail(function (jqXHR, textStatus, errorThrown){ | |
// log the error to the console | |
console.error( | |
"The following error occured: "+ | |
textStatus, errorThrown | |
); | |
}); | |
// callback handler that will be called regardless | |
// if the request failed or succeeded | |
request.always(function () { | |
// reenable the inputs | |
$inputs.prop("disabled", false); | |
}); | |
// prevent default posting of form | |
event.preventDefault(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment