@dpsys/ajax-form
v1.1.6
Published
A lightweight handler for submitting HTML forms via AJAX
Maintainers
Readme
Ajax Form
A lightweight handler for submitting HTML forms via AJAX.
Supports CommonJS (CJS) and ES Modules (ESM).
Installation
npm i @dpsys/ajax-formExample Usage
Given form:
<form name="my_form" method="post">
<input type="text" name="my_form[something]" required="required">
<button type="submit" name="my_form[submit]">Submit</button>
</form>Then in JS:
This example uses Axios. Feel free to use any other AJAX implementation.
import ajaxForm from '@dpsys/ajax-form';
import axios from 'axios';
ajaxForm('my_form').setSubmitCallback( (axForm, formData) =>
{
axios.post('/some-route', formData)
.then( (resp) =>
{
if (resp.data.formErrors)
{
axForm.showErrors(resp.data.formErrors);
}
else if (resp.data.success)
{
// Do something...
axForm.reset();
}
});
});Reference
ajaxForm(form)
Creates and returns an AjaxForm instance for handling the specified form.
Parameters:
form: A form element (HTMLElement), CSS selector (string), or form name (string).
Returns: An AjaxForm instance.
Throws: Error if the form is not found or invalid.
AjaxForm Methods
setSubmitCallback(callback)
Sets a callback function to handle form submission.
Parameters:
callback(axForm, formData): Function called on submit.axFormis the instance,formDatais a FormData object.
showErrors(errors)
Displays error messages by inserting <span> elements after input fields.
Parameters:
errors: Array of objects with{field_id: string, message: string}.
getForm()
Returns the form element.
reset()
Resets the form to its default values.
