I am trying to send data from a form to a database. Here is the form I am using:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form’s data and submit it to a PHP script (an example, form.php)?
Basic usage of
.ajaxwould look something like this:HTML:
jQuery:
Note: Since jQuery 1.8,
.success(),.error()and.complete()are deprecated in favor of.done(),.fail()and.always().Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a
$(document).ready()handler (or use the$()shorthand).Tip: You can chain the callback handlers like this:
$.ajax().done().fail().always();PHP (that is, form.php):
Note: Always sanitize posted data, to prevent injections and other malicious code.
You could also use the shorthand
.postin place of.ajaxin the above JavaScript code: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.