jQuery Validate Plugin Integration
The jQuery Validate plugin provides an alternative to frames for form submission whose output needs to be displayed on the same page, usually a target <div>. This provides a modern look which also happens to be standards compliant. One problem with this modern layout however is with further jQuery manipulation, where the library tries to catalogue page objects through the $(document).ready(function(){.
As an example, say one wants to use the Colorbox plugin, and the event is assigned to the elements in the $(document).ready(function(){. Unfortunately the elements don't exist on the page until the form is submitted, and therein lies the problem. We start by understanding the jQuery Validate setup:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.colorbox.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
$("#siteForm").validate({
errorPlacement: function(error, element) {
error.insertAfter($('#generatorResults'));
},
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
$.post('generate-sites.php', $("#siteForm").serialize(), function(data) {
$('#results').html(data);
});
}
});
<form method="post" action="form-handler.php" name="siteForm" id="siteForm">
<div>
<input type="text" id="answer" />
<input type="submit" value="Submit" />
</div>
</form>
<div id="results"></div>
$response = $_POST["answer"];
echo ($response);
?>
This is all fine and good to this point. But notice we have also loaded the Colorbox plugin. If our form handler produces markup that triggers a Colorbox event, we'll have to reinitialize the new page elements. This is done simply by adding the call to the .post function after the $results data has been created. Say our handler did this:
$response = $_POST["answer"];
echo ('<a href="image" rel="colorBox">' . $response . '<a>');
?>
To activate the Colorbox function, we add the call in the .post:
// do other stuff for a valid form
$.post('generate-sites.php', $("#siteForm").serialize(), function(data) {
$('#generatorResults').html(data);
$("a[rel='colorBox']").colorbox();
});
}
And that's it. I hope it helps!