@github/remote-form
v0.4.3
Published
Decorator that will submit a form over AJAX
Downloads
1,005
Readme
remote-form
A function that will enable submitting forms over AJAX.
The function will make a request based on the form using window.fetch
with the payload encoded as URL parameters if the form method is a GET
and FormData
for all the other methods.
The request object is available in the callback function, allowing the headers and body to be modified before the request is sent.
Installation
$ npm install --save @github/remote-form
Usage
import {remoteForm} from '@github/remote-form'
// Make all forms that have the `data-remote` attribute a remote form.
remoteForm('form[data-remote]', async function(form, wants, request) {
// Before we start the request
form.classList.remove('has-error')
form.classList.add('is-loading')
let response
try {
response = await wants.html()
} catch (error) {
// If the request errored, we'll set the error state and return.
form.classList.remove('is-loading')
form.classList.add('has-error')
return
}
// If the request succeeded we can do something with the results.
form.classList.remove('is-loading')
form.querySelector('.results').innerHTML = response.html
})
<form action="/signup" method="post" data-remote>
<label for="username">Username</label>
<input id="username" type="text">
<label for="password">Username</label>
<input id="password" type="password">
<button type="submit">Log in</button>
<div class="results"></div>
</form>
Browser support
Browsers without native custom element support require a polyfill.
- Chrome
- Firefox
- Safari
- Microsoft Edge
Development
npm install
npm test
License
Distributed under the MIT license. See LICENSE for details.