Skip to content

Instantly share code, notes, and snippets.

@Scemist
Last active October 6, 2022 17:06
Show Gist options
  • Save Scemist/7874a558b0f757c789794b3bbdcba0aa to your computer and use it in GitHub Desktop.
Save Scemist/7874a558b0f757c789794b3bbdcba0aa to your computer and use it in GitHub Desktop.
Thirty Lines JavaScript Ajax Micro Framework
const Ajax = (parameters) => ({
to: parameters.to ?? null,
method: parameters.method ?? 'GET',
data: parameters.data ?? null,
callback: parameters.callback ?? null,
callbackData: parameters.callbackData ?? null,
send: function () {
const xhr = new XMLHttpRequest()
let to = this.to
if (this.method == 'GET' && this.data instanceof Array) {
to += '?'
this.data.forEach(data => to += `${data.name}=${data.value}`)
}
xhr.open(this.method, window.location.origin + to)
xhr.setRequestHeader('Content-Type', 'application/json')
if (this.method == 'POST' || this.method == 'PUT' || this.method == 'PATCH' || this.method == 'DELETE')
xhr.setRequestHeader('x-csrf-token', document.querySelector('meta[name=csrf-token]').content)
if (this.callback instanceof Function)
xhr.onload = _ => this.callback(
xhr.responseText,
xhr.status,
this.callbackData
)
xhr.send(this.data)
}
})
const Users = {
finishCreation(response, status, callbackData) {
console.log(`Finish creating user ${callbackData} with code ${status}. Response: ${response}`)
}
}
const newUser = JSON.stringify({
name: 'John Silver',
age: 25,
})
Ajax({
to: 'https://dashboard.com/users/create',
data: newUser,
callback: Users.finishCreation,
callbackData: userName,
method: 'POST',
}).send()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment