Quick overview of the jQuery Form Plugin (from their website):
The jQuery Form Plugin allows you to easily and
unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm
and ajaxSubmit, gather information from the form element to determine
how to manage the submit process. Both of these methods support numerous
options which allows you to have full control over how the data is
submitted. Submitting a form with AJAX doesn’t get any easier than this!
Ok, now that you have some background, lets begin the tutorial!
1. Start by Building a Form
With the jQuery Form Plugin, you can make very complex forms and the
plugin has no problem gathering all the form data and sending it over
AJAX. For this tutorial however, lets keep it simple and create a
contact form (Name, Email, and Message fields). All the fields in the
form will be required.
Make sure to include the following attributes in your form tag, plus a
DIV tag which will be used to display success/error messages.
<form method="post" action="submit.php" id="contact-us">
<div id="contact-us-message"></div>
<div class="input-box">
<label>Name</label>
<input type="text" name="name" />
</div>
<div class="input-box">
<label>Email</label>
<input type="text" name="email" />
</div>
<div class="input-box">
<label>Message</label>
<textarea name="message"></textarea>
</div>
<div class="submit">
<input type="submit" value="Submit" />
</div>
</form>
Note: The id attribute for the first DIV tag is
the id attribute of the FORM tag + “-message”. In the JavaScript source
provided in this tutorial, we have setup this custom convention, which
helps to ensure the naming of elements is kept consistent throughout the
application.
2. Create External JavaScript File (application.js) and Include into Page
Make sure to also include the
jQuery and
jQuery Form Plugin library files exactly in the order shown below.
<head>
...
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript" src="application.js"></script>
</head>
3. Add JavaScript Code into application.js
The first section of code contains our
setupAjaxForm
class…it’s a small amount of code, but it accomplishes a lot. First,
the class sets up the appropriate options for the jQuery Form Plugin. In
addition, once a form is submitted, the class handles the JSON response
and displays the results above the form.
Feel free to expand upon this class for your own uses :).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| function setupAjaxForm(form_id, form_validations){
var form = '#' + form_id;
var form_message = form + '-message';
// en/disable submit button
var disableSubmit = function(val){
$(form + ' input[type=submit]').attr('disabled', val);
};
// setup loading message
$(form).ajaxSend(function(){
$(form_message).removeClass().addClass('loading').html('Loading...').fadeIn();
});
// setup jQuery Plugin 'ajaxForm'
var options = {
dataType: 'json',
beforeSubmit: function(){
// run form validations if they exist
if(typeof form_validations == "function" && !form_validations()) {
// this will prevent the form from being subitted
return false;
}
disableSubmit(true);
},
success: function(json){
/**
* The response from AJAX request will look something like this:
* {"type" : "success", "message" : "Thank-You for submitting the form!"}
* Once the jQuery Form Plugin receives the response, it evaluates the string into a JavaScript object, allowing you to access
* object members as demonstrated below.
*/
$(form_message).hide();
$(form_message).removeClass().addClass(json.type).html(json.message).fadeIn('slow');
disableSubmit(false);
if(json.type == 'success')
$(form).clearForm();
}
};
$(form).ajaxForm(options);
}
|
Now we need to instantiate the class to make the form active. The
instantiation of the class is wrapped by the jQuery event handler which
fires when the document is ready.
36
37
38
| $(document).ready(function() {
new setupAjaxForm('contact-us');
});
|
If you would like to add in JavaScript validations before the form is submitted, using the following code.
36
37
38
39
40
| $(document).ready(function() {
new setupAjaxForm('contact-us', function(){
// field validations go here, make sure to return true (validates) / false (fails).
});
});
|
4. Setup back-end PHP script for form processing
The below PHP script is very generic and basic (not even
object-oriented). At minimum, the script shows the basic work flow to
process POST data and return a JSON response. I would recommend taking
the response variable and moving it to a class to ensure your response
hash stays consistent throughout your application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| <?php
if($_POST){
// response hash
$response = array('type'=>'', 'message'=>'');
try{
// do some sort of data validations, very simple example below
$required_fields = array('name', 'email', 'message');
foreach($required_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, field validations are ok
// now add to data to DB, Send Email, ect.
// let's assume everything is ok, setup successful response
$response['type'] = 'success';
$response['message'] = 'Thank-You for submitting the form!';
}catch(Exception $e){
$response['type'] = 'error';
$response['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($response);
exit;
}
?>
|
5. Add CSS styles
Our JavaScript code requires two CSS classes, “success” and “error”
to be setup for the form results. At this point, you should have a
functioning form, but it’s ugly! Spend some time adding some visual
styles to match your project and your done! If your stuck, download the
files provided at the bottom of this tutorial for some additional
guidance.
Hope you enjoyed and found this tutorial useful. As always, if you
have any questions, comments, or feedback on improving this site, feel
free to leave a comment below.