Sha256: ec24d1f49fd88bd17a554cc4e7b11216982ece6838571ace5c46f16264f07013

Contents?: true

Size: 1.54 KB

Versions: 53

Compression:

Stored size: 1.54 KB

Contents

function buildPromise(xhr) {
  return new Promise((resolve, reject) => {
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 400) {
        try {
          resolve({
            data: JSON.parse(xhr.responseText),
            status: xhr.status
          })
        } catch (error) {
          reject(error)
        }
      } else {
        try {
          reject(JSON.parse(xhr.responseText))
        } catch (error) {
          reject(error)
        }
      }
    }
    xhr.onerror = () => {
      reject(new Error("An error occurred during the transaction"))
    }
  })
}

function getToken() {
  const metaTag = document.querySelector('meta[name="csrf-token"]')
  return metaTag.attributes.content.textContent
}

export function get(url, params) {
  return ajax("GET", url, params)
}

export function patch(url, data) {
  return ajax("PATCH", url, data)
}

export function post(url, data) {
  return ajax("POST", url, data)
}

export default function ajax(method, path, data) {
  const xhr = new XMLHttpRequest()
  const promise = buildPromise(xhr)
  const url = new URL(window.location.origin + path)

  if (data && method.toLowerCase() === "get") {
    url.search = new URLSearchParams(data).toString()
  }

  xhr.open(method, url.toString())
  xhr.setRequestHeader("Content-type", "application/json; charset=utf-8")
  xhr.setRequestHeader("Accept", "application/json")
  xhr.setRequestHeader("X-CSRF-Token", getToken())

  if (data && method.toLowerCase() !== "get") {
    xhr.send(JSON.stringify(data))
  } else {
    xhr.send()
  }

  return promise
}

Version data entries

53 entries across 53 versions & 1 rubygems

Version Path
alchemy_cms-7.0.15 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-6.1.10 package/src/utils/ajax.js
alchemy_cms-7.0.14 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.13 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.12 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.11 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.10 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.9 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.8 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.7 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.6 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.5 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.4 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.3 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-6.1.9 package/src/utils/ajax.js
alchemy_cms-7.0.2 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-6.1.8 package/src/utils/ajax.js
alchemy_cms-6.1.7 package/src/utils/ajax.js
alchemy_cms-7.0.1 app/javascript/alchemy_admin/utils/ajax.js
alchemy_cms-7.0.0 app/javascript/alchemy_admin/utils/ajax.js