-
Notifications
You must be signed in to change notification settings - Fork 3
AJAX Form Validation
ShiftLib can facilitate form validation and submission via AJAX.
For this example we have a table called enquiries which has id
, date
, name
, email
and enquiry
fields.
The name
, email
and enquiry
fields have been marked as required in the admin system.
<?php
// handle form submission
if (count($_POST)) {
// set cms section for fields and validation
$cms->set_section('enquiries');
// handle ajax form validation
$cms->submit_handler();
}
?>
<h1>Contact form</h1>
<form method="post" sl-validate sl-hide sl-target="#thanks">
<p>
<input type="text" name="name" placeholder="name">
</p>
<p>
<input type="email" name="email" placeholder="email">
</p>
<p>
<textarea name="enquiry" placeholder="enquiry"></textarea>
</p>
<button type="submit">Submit</button>
</form>
<div id="thanks" style="display: none;">
<p>
Thanks {{ name }}, we will be in touch..
</p>
</div>
<?php
load_js('shiftlib');
?>
When submitted the validation will be checked, any errors will be displayed next to the relevant field. Upon successful submission, the form will be hidden and the handlebars template is displayed with the variables replaced. This is achieved via several magical attributes:
Forms with this attribute will be validated by ShiftLib.
Forms with this attribute will be hidden upon successful submission.
References an element which will be displayed upon successful submission. Can contain a handlebars template to display the returned values.