Sha256: c5b8f83c64d2ebe84b6ddc6e7697f494a13cfdb311888c8cf045e5184dfc9fca

Contents?: true

Size: 1.33 KB

Versions: 12

Compression:

Stored size: 1.33 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 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

12 entries across 12 versions & 1 rubygems

Version Path
alchemy_cms-6.0.0.pre.rc6 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.rc5 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.rc4 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.rc3 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.rc2 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.rc1 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.b6 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.b5 package/src/utils/ajax.js
alchemy_cms-6.0.0.pre.b4 package/src/utils/ajax.js
alchemy_cms-6.0.0.b3 package/src/utils/ajax.js
alchemy_cms-6.0.0.b2 package/src/utils/ajax.js
alchemy_cms-6.0.0.b1 package/src/utils/ajax.js