Sometimes you may have a form and want to submit it using ajax.
Suppose you have this simple form -
<form id="ajax_form" action="form_action.php">
<label for="name">Name :</label>
<input name="name" id="name" type="text" />
<label for="name">Email :</label>
<input name="email" id="email" type="text" />
<input type="submit" value="Submit" />
</form>
The following jQuery code can be used (within a $(document).ready
call) -
$('#ajax_form').submit(function(event){
event.preventDefault();
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function(data) {
// Do something with the response
},
error: function(error) {
// Do something with the error
}
});
});
Explanation
var $form = $(this)
- the form, cached for reuse$('#ajax_form').submit(function(event){
- When the form with ID
"ajax_form" is submitted run this function and pass the event as a
parameter.event.preventDefault();
- Prevent the form from submitting normally (Alternatively we can use return false
after the ajax({});
statement, which will have the same effect)url: $form.attr('action'),
- Get the value of the form's "action" attribute and use it for the "url" property.data: $form.serialize(),
- Converts the inputs within the form into a string suitable for sending to the server. In this case it will return something like "name=Bob&[email protected]"