Remember my tutorial on implementing input arrays in jQuery? It seems that there is much simpler way of doing it without too much hassle coding the individual parameters, and remebering all the field #id’s. That is if you don’t mind loading another 29KB JavaScript library. Introducing the Form Plug-in for JQuery, this library will be of great help for very large forms that needs to be processed via AJAX
For this tutorial, we will use the same form as the one before. The only difference is that we no longer need to reference each field by its own #id, rather we can reference it by giving the #id to the main form itself! For now, lets just name our form prog_form. A good rule of thumb is to design the form as if it were just a regular HTML form:
Select your favorite programming languages:<br>
<form id="prog_form" method="POST" action="post_prog.php">
<input type="checkbox" name="prog[]" value="C">C<br>
<input type="checkbox" name="prog[]" value="C++">C++<br>
<input type="checkbox" name="prog[]" value="Java">Java<br>
<input type="checkbox" name="prog[]" value="VB.NET">VB.NET<br>
<input type="checkbox" name="prog[]" value="PHP">PHP<br>
<input type="checkbox" name="prog[]" value="Perl">Perl<br>
<input type="checkbox" name="prog[]" value="Ruby">Ruby<br>
<input type="checkbox" name="prog[]" value="Python">Python<br>
<input type="submit" id="submit_prog" value='Submit' />
</form>
Next step is once again, we need to define the container where our AJAX response will show up
<div id="content">The AJAX response will show up here.</div>
for this tutorial, we’re going to use the same PHP backend as we did last time. We’ll be using post_prog.php once again:
post_prog.php
You have selected:<br>
<?php
foreach ($_POST['prog'] as $prog)
{
$prog = htmlspecialchars($prog, ENT_QUOTES);
echo $prog, '', "\\n";
}
?>
Now here comes the good part: handling the form. First we must load the JQuery library and the Form library plug-in by including this code inside the <head> element of our page:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
Finally, now that we have loaded the required scripts, now its time to handle our form by writing this script inside our page’s <body>:
<script type="text/javascript">
$(document).ready(function()
{
$('#prog_form').ajaxForm({
target: '#content'
});
});
</script>
Yes its that simple! The magic basically happens here:
$('#prog_form').ajaxForm({
target: '#content'
});
what basically happens is that our form #prog_form will now be submitted through AJAX.
The target: attribute of ajaxForm will define where the AJAX callback will be displayed. In this case we set it to the #container we just made. Now that’s very easy, isn’t it?
View the Tutorial Demo
Download Source Codes









