Skip to content

AJAX Form Validation

Adam Jimenez edited this page Apr 22, 2024 · 3 revisions

ShiftLib can facilitate form validation and submission via AJAX.

form validation

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:

sl-validate

Forms with this attribute will be validated by ShiftLib.

sl-hide

Forms with this attribute will be hidden upon successful submission.

sl-target

References an element which will be displayed upon successful submission. Can contain a handlebars template to display the returned values.

Clone this wiki locally