Skip to content

Instantly share code, notes, and snippets.

@Septdir
Last active April 5, 2020 17:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Septdir/18794105169dc28875f76cfa0a40106d to your computer and use it in GitHub Desktop.
Save Septdir/18794105169dc28875f76cfa0a40106d to your computer and use it in GitHub Desktop.
Ajax request for joomla
let request = new XMLHttpRequest(),
requestUrl = '', // Указываем url запроса
formData = new FormData(); // Перадаем <form> или просто добавляем ниже через append что нужно
request.open('POST', requestUrl);
request.send(formData);
request.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
let response = false;
try {
response = JSON.parse(this.response);
} catch (e) {
response = false;
console.error(request.status + ' ' + e.message);
return;
}
if (response.success) {
console.log(response.data);
//document.dispatchEvent(new Event('DOMContentLoaded', {'bubbles': true})); // Запускам ивенты если надо
} else {
console.error(response.message);
}
} else if (this.readyState === 4 && this.status !== 200) {
console.error(request.status + ' ' + request.message);
}
};
@b2z
Copy link

b2z commented Apr 5, 2020

Я бы ещё добавил перед request.send(formData); отправку csrf токена

let token = Joomla.getOptions('csrf.token', '');
if (token) {
    request.setRequestHeader('X-CSRF-Token', token);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment