Skip to content

Development: AJAX API

Sami Mokaddem edited this page Jan 18, 2021 · 7 revisions

Overview

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.

Quick functions

Function commonly used throughout the application

  1. quickFetchURL simply fetches the remote
// quickFetchURL(url, options={})
AJAXApi.quickFetchURL('/users/index').then(text => {
    console.log(text)
})
  1. quickFetchJSON simply fetches the remote JSON
// quickFetchJSON(url, options={})
AJAXApi.quickFetchURL('/users/view/1').then(json => {
    console.log(json)
})
  1. 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)
})
  1. 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)
})
  1. 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)
})

AJAXApi usage

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'))