Skip to content

Forms

Supersonic Forms provides a comprehensive solution for handling form submissions on static websites with built-in validation, AJAX submission, captcha protection, and flexible response handling.

Here’s a most basic contact form example:

<form id="contact-form">
<input type="text" name="name" id="name" required>
<input type="email" name="email" id="email" required>
<textarea name="message" id="message" required></textarea>
<input type="text" name="numb_captcha" id="captcha" required>
<button type="submit" id="submit-btn">Send Message</button>
</form>
<script>
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
method: 'POST'
});
</script>
OptionTypeRequiredDescription
formIdstringYesThe ID of the form element (without #)
submitButtonstringYesCSS selector for the submit button
ajaxUrlstringYesURL endpoint to send form data to
methodstringNoHTTP method: 'POST' or 'GET' (default: 'POST')
OptionTypeRequiredDescription
dataobjectNoAdditional data to include with form submission
indicatorstringNoCSS selector for loading indicator element
responseTypestringNoResponse handler type: 'default' or 'swal' (default: 'default')
callbackfunctionNoCustom callback function to handle response
recaptchaboolean/stringNoEnable Google reCAPTCHA v3
recaptcha_site_keystringNoYour Google reCAPTCHA v3 site key
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
method: 'POST',
data: {
source: 'website',
page: 'contact-us'
},
indicator: '#loading-spinner',
responseType: 'swal',
callback: (response) => {
if (response.success) {
console.log('Form submitted successfully!');
}
}
});

Supersonic includes built-in client-side validation that runs automatically before form submission.

Add the required attribute to any input to make it mandatory:

<input type="text" name="name" required>

Forms automatically watch for field changes and display errors in real-time. Validation triggers on:

  • keyup - As the user types
  • change - When field value changes
  • blur - When field loses focus

Validation errors are displayed automatically below each field:

<div>
<input type="email" name="email" required>
<!-- Error message appears here -->
<span class="error-message">Invalid email address</span>
</div>

The parent <div> receives an .error class when validation fails, allowing you to style error states:

.error input {
border-color: red;
}
.error-message {
color: red;
}

Supersonic includes a simple math-based captcha to prevent spam submissions without requiring external services.

Add an input field with the name numb_captcha:

<div>
<label for="captcha">What is the sum?</label>
<input type="text" name="numb_captcha" id="captcha" required>
</div>

The library automatically:

  1. Generates two random numbers
  2. Sets the input placeholder to show the equation (e.g., “7 + 3 = ?”)
  3. Adds hidden fields with the numbers for server-side verification
  4. Validates the answer before submission

When you initialize the form, the captcha is automatically generated:

// Captcha is set up automatically
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact'
});

The user sees a placeholder like “7 + 3 = ?” and must enter “10” to pass validation.

Forms are submitted via the Fetch API without page reload:

const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
method: 'POST'
});

Show a loading spinner during submission:

<div id="loading" class="hidden">
<span>Sending...</span>
</div>
<script>
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
indicator: '#loading'
});
</script>

The indicator automatically:

  • Removes the hidden class when submitting
  • Adds it back after receiving response

Include extra data with every submission:

const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
data: {
utm_source: 'google',
utm_campaign: 'summer-sale',
page_url: window.location.href,
timestamp: new Date().toISOString()
}
});

File inputs are automatically handled:

<form id="upload-form">
<input type="file" name="attachment" accept=".pdf,.doc,.docx">
<button type="submit" id="upload-btn">Upload</button>
</form>
<script>
const form = new supersonic.newForm({
formId: 'upload-form',
submitButton: '#upload-btn',
ajaxUrl: '/api/upload',
method: 'POST'
});
</script>

Protect your forms with Google reCAPTCHA v3 (invisible captcha).

  1. Get your reCAPTCHA v3 keys from Google reCAPTCHA Admin
  2. Add the reCAPTCHA script to your page:
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>
  1. Configure the form:
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
recaptcha: true,
recaptcha_site_key: 'YOUR_SITE_KEY'
});

The reCAPTCHA token is automatically included in the form data as recaptcha_response.

Your backend must verify the token:

// Example Node.js/Express
const verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
const response = await fetch(verifyUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `secret=YOUR_SECRET_KEY&response=${recaptchaToken}`
});
const data = await response.json();
if (data.success && data.score > 0.5) {
// Valid submission
}

Your server should return JSON responses in this format:

{
"success": true,
"message": "Thank you! Your message has been sent.",
"body": "<p>We'll get back to you within 24 hours.</p>",
"errors": []
}

Or for errors:

{
"success": false,
"message": "Submission failed",
"errors": [
{
"name": "email",
"error": "Email address is already registered"
}
]
}

By default, successful submissions:

  • Clear the form fields
  • Hide any error messages
  • Trigger custom events
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
responseType: 'default' // default handler
});

Use beautiful modal popups for responses (requires SweetAlert2).

Supersonic comes with SweetAlert2 integration out of the box, just has to be enabled when initializing supersonic instances.

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
responseType: 'swal'
});
</script>

Success responses show a modal with the message or body content. Error responses show an error toast notification.

Handle responses with your own logic:

const form = new supersonic.newForm({
formId: 'contact-form',
submitButton: '#submit-btn',
ajaxUrl: '/api/contact',
callback: (response) => {
if (response.success) {
// Redirect to thank you page
window.location.href = '/thank-you';
} else {
// Show custom error message
alert(response.message);
}
}
});

When using a callback, the default response handler is not executed.

Supersonic Forms dispatches custom events you can listen to:

Triggered before the form is submitted. Cancel submission by calling preventDefault():

document.addEventListener('supersonic:FormSubmitBefore', (e) => {
const formData = e.detail;
console.log('About to submit:', formData);
// Cancel submission conditionally
if (someCondition) {
e.preventDefault();
}
});

Triggered after receiving a response:

document.addEventListener('supersonic:FormSubmitAfter', (e) => {
const response = e.detail;
console.log('Response received:', response);
// Track with analytics
if (response.success) {
gtag('event', 'form_submission', {
form_id: response.form_css_id
});
}
});

Triggered only on successful responses:

document.addEventListener('supersonic:AjaxResponseSuccess', (e) => {
const response = e.detail;
console.log('Success:', response.message);
});

Triggered only on error responses:

document.addEventListener('supersonic:AjaxResponseError', (e) => {
const response = e.detail;
console.error('Error:', response.message);
});

Here’s a full, production-ready contact form:

<form id="contact-form">
<div class="form-group">
<label for="name">Full Name *</label>
<input type="text" name="name" id="name" required>
</div>
<div class="form-group">
<label for="email">Email Address *</label>
<input type="email" name="email" id="email" required>
</div>
<div class="form-group">
<label for="message">Message *</label>
<textarea name="message" id="message" rows="5" required></textarea>
</div>
<div class="form-group">
<label for="captcha">Math Challenge *</label>
<input type="text" name="numb_captcha" id="captcha" required placeholder="Answer will appear here">
</div>
<div id="loading-indicator" class="hidden">
<div class="loading-spinner"></div>
Sending your message...
</div>
<button type="submit" id="submit-btn">Send Message</button>
</form>

Supersonic Forms also provides utility functions for advanced use cases:

Manually clear all form fields:

// Available on global supersonic object
supersonic.form.clearForm('contact-form');

Programmatically set form field values:

supersonic.form.setFieldValues('contact-form', {
name: 'John Doe',
email: 'john@example.com',
message: 'Hello!'
});

Validate a specific field:

const field = document.querySelector('[name="email"]');
const error = supersonic.form.validation.validateField(field);
if (error) {
console.log(`Error in ${error.name}: ${error.error}`);
}

Manually enable real-time validation:

supersonic.form.watch('contact-form');

Manually generate a number captcha:

supersonic.form.numbCaptcha('contact-form');

If you need to remove event listeners (e.g., in a single-page application):

const form = new supersonic.newForm({...});
// Later, when component unmounts
form.destroy();

Customize validation messages for different languages:

// Set custom messages before initializing form
supersonic.i18n.set('invalid_email', 'Por favor, introduce un email válido');
supersonic.i18n.set('required_field', 'Este campo es obligatorio');
// Then initialize your form
const form = new supersonic.newForm({...});