-
Notifications
You must be signed in to change notification settings - Fork 18
Development: AJAX API
Sami Mokaddem edited this page Jan 18, 2021
·
7 revisions
The api-helper.js Provides helpers to perform AJAX requests against cerebrate. It can provide feedback about the progress of the operation to the user and reload part of the page. It's basically a promise-based wrapper using the Fetch API to perform requests.
Function commonly used throughout the application
-
quickFetchURL
simply fetches the remote
// quickFetchURL(url, options={})
AJAXApi.quickFetchURL('/users/index').then(text => {
console.log(text)
})
-
quickFetchJSON
simply fetches the remote JSON
// quickFetchJSON(url, options={})
AJAXApi.quickFetchURL('/users/view/1').then(json => {
console.log(json)
})
-
quickFetchForm
fetches the HTML at the provided URL, then extract the form. Resolves to the HTMLFormElement if successful
// quickFetchForm(url, options={})
AJAXApi.quickFetchForm('/users/add').then(formElement => {
document.body.append(formElement)
})
-
quickPostForm
POST a form, dataToMerge can be used to modify form values on-the-fly
// quickPostForm(form, dataToMerge={}, options={})
AJAXApi.quickPostForm(form, {uuid: genUUID()}).then(json => {
console.log(json)
})
-
quickFetchAndPostForm
Fetch a form, dataToMerge can be used to modify form values on-the-fly and then POST it
// quickFetchAndPostForm(url, dataToMerge={}, options={})
AJAXApi.quickFetchAndPostForm('/users/toggle/1/enabled).then(json => {
console.log(json)
})
An AJAXApi
can be passed a configuration object to describe how the feedback should be given to users.
// options
{
provideFeedback: true, // Should a toast be used to provide feedback upon request fulfillment
statusNode: false, // The node on which the loading overlay should be placed
statusNodeOverlayConfig: {}, // The configuration of the overlay applied on the status node
errorToastOptions: {}, // Options to be passed to the toaster for error
successToastOptions: {} // Options to be passed to the toaster for success
}
Example
const api = new AJAXApi({
statusNode: document.getElementById('myButton')
})
api.postForm(document.getElementById('myForm'))