Sha256: 47ba6a402cde54bb104f9fa04a53f23ea43465c317a213a609ccba8af3835277

Contents?: true

Size: 1.13 KB

Versions: 41

Compression:

Stored size: 1.13 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, url, data) {
  const xhr = new XMLHttpRequest()
  const promise = buildPromise(xhr)

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

  if (data) {
    xhr.send(JSON.stringify(data))
  } else {
    xhr.send()
  }

  return promise
}

Version data entries

41 entries across 41 versions & 1 rubygems

Version Path
alchemy_cms-5.3.1 package/src/utils/ajax.js
alchemy_cms-5.3.0 package/src/utils/ajax.js
alchemy_cms-5.2.7 package/src/utils/ajax.js
alchemy_cms-5.2.6 package/src/utils/ajax.js
alchemy_cms-5.1.10 package/src/utils/ajax.js
alchemy_cms-5.0.10 package/src/utils/ajax.js
alchemy_cms-5.2.5 package/src/utils/ajax.js
alchemy_cms-5.1.9 package/src/utils/ajax.js
alchemy_cms-5.0.9 package/src/utils/ajax.js
alchemy_cms-5.2.4 package/src/utils/ajax.js
alchemy_cms-5.1.8 package/src/utils/ajax.js
alchemy_cms-5.0.8 package/src/utils/ajax.js
alchemy_cms-5.0.7 package/src/utils/ajax.js
alchemy_cms-5.1.7 package/src/utils/ajax.js
alchemy_cms-5.2.3 package/src/utils/ajax.js
alchemy_cms-5.1.6 package/src/utils/ajax.js
alchemy_cms-5.0.6 package/src/utils/ajax.js
alchemy_cms-5.2.2 package/src/utils/ajax.js
alchemy_cms-5.1.5 package/src/utils/ajax.js
alchemy_cms-5.0.5 package/src/utils/ajax.js