HTML:
<formid="foo"><labelfor="bar">A bar</label><inputid="bar"name="bar"type="text"value=""/><inputtype="submit"value="Send"/></form>
JavaScript:
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").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();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
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 occurred: "+
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();
});
PHP (that is, form.php):
// You can access the values posted by jQuery.ajax// through the global variable $_POST, like this:
$bar = $_POST['bar'];
Note: Always sanitize posted data, to prevent injections and other malicious code.
You could also use the shorthand .post
in place of .ajax
in the above JavaScript code:
$.post('/form.php', serializedData,function(response){// Log the response to the console
console.log("Response: "+response);});
Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.