export class Ajax { public data: object public fail: Function public method: string = 'GET' public success: Function public URL: string public xhr: XMLHttpRequest constructor(properties: object) { this.setProperties(properties) this.xhr = new XMLHttpRequest() return this } public setProperties(properties: object): Ajax { for (let key in properties) { this[key] = properties[key] } return this } public send(): Ajax { let onStateChange: Function = (): void => { if (this.xhr.readyState === XMLHttpRequest.DONE) { let data : object if (this.xhr.responseText) { data = JSON.parse(this.xhr.responseText) } if (this.xhr.status === 200) { this.success(data, this.xhr) } else { this.fail(data, this.xhr) } } this.xhr.open(this.method, this.URL, true) if (this.method === 'POST') { this.xhr.setRequestHeader('Content-Type', 'application/jsoncharset=UTF-8') } if (typeof this.data !== 'undefined') { this.xhr.send(JSON.stringify(this.data)) } else { this.xhr.send() } } this.xhr.onreadystatechange = onStateChange.bind(this) return this } }