AJAX: Add some code that can be reused to display AJAX request errors

Also use this to add groups to the left menu
This commit is contained in:
Maxim Leshchenko 2021-12-25 18:03:21 +02:00
parent efa89e075f
commit 566759327e
No known key found for this signature in database
GPG key ID: BB9C44A8733FBEEE
4 changed files with 62 additions and 18 deletions

View file

@ -39,14 +39,26 @@ abstract class OpenVKPresenter extends SimplePresenter
Session::i()->set("_tempTheme", $theme);
}
protected function flashFail(string $type, string $title, ?string $message = NULL, ?int $code = NULL): void
protected function flashFail(string $type, string $title, ?string $message = NULL, ?int $code = NULL, bool $json = false): void
{
$this->flash($type, $title, $message, $code);
$referer = $_SERVER["HTTP_REFERER"] ?? "/";
header("HTTP/1.1 302 Found");
header("Location: $referer");
exit;
if($json) {
$this->returnJson([
"success" => $type !== "err",
"flash" => [
"type" => $type,
"title" => $title,
"message" => $message,
"code" => $code,
],
]);
} else {
$this->flash($type, $title, $message, $code);
$referer = $_SERVER["HTTP_REFERER"] ?? "/";
header("HTTP/1.1 302 Found");
header("Location: $referer");
exit;
}
}
protected function logInUserWithToken(): void
@ -120,7 +132,7 @@ abstract class OpenVKPresenter extends SimplePresenter
$this->flashFail("err", tr("captcha_error"), tr("captcha_error_comment"));
}
protected function willExecuteWriteAction(): void
protected function willExecuteWriteAction(bool $json = false): void
{
$ip = (new IPs)->get(CONNECTING_IP);
$res = $ip->rateLimit();
@ -131,7 +143,7 @@ abstract class OpenVKPresenter extends SimplePresenter
exit("Хакеры? Интересно...");
}
$this->flashFail("err", tr("rate_limit_error"), tr("rate_limit_error_comment", OPENVK_ROOT_CONF["openvk"]["appearance"]["name"], $res));
$this->flashFail("err", tr("rate_limit_error"), tr("rate_limit_error_comment", OPENVK_ROOT_CONF["openvk"]["appearance"]["name"], $res), NULL, $json);
}
}
@ -241,4 +253,13 @@ abstract class OpenVKPresenter extends SimplePresenter
Session::i()->set("_error", NULL);
}
}
protected function returnJson(array $json): void
{
$payload = json_encode($json);
$size = strlen($payload);
header("Content-Type: application/json");
header("Content-Length: $size");
exit($payload);
}
}

View file

@ -101,11 +101,11 @@ final class UserPresenter extends OpenVKPresenter
$this->notFound();
if(!$club->canBeModifiedBy($this->user->identity ?? NULL))
$this->flashFail("err", "Ошибка доступа", "У вас недостаточно прав, чтобы изменять этот ресурс.");
$this->flashFail("err", "Ошибка доступа", "У вас недостаточно прав, чтобы изменять этот ресурс.", NULL, true);
$isClubPinned = $this->user->identity->isClubPinned($club);
if(!$isClubPinned && $this->user->identity->getPinnedClubCount() > 10)
$this->flashFail("err", "Ошибка", "Находится в левом меню могут максимум 10 групп");
$this->flashFail("err", "Ошибка", "Находится в левом меню могут максимум 10 групп", NULL, true);
if($club->getOwner()->getId() === $this->user->identity->getId()) {
$club->setOwner_Club_Pinned(!$isClubPinned);
@ -118,10 +118,9 @@ final class UserPresenter extends OpenVKPresenter
}
}
if($isClubPinned)
$this->flashFail("succ", "Операция успешна", "Группа " . $club->getName() . " была успешно удалена из левого меню");
else
$this->flashFail("succ", "Операция успешна", "Группа " . $club->getName() . " была успешно добавлена в левое меню");
$this->returnJson([
"success" => true
]);
}
function renderEdit(): void

View file

@ -320,7 +320,7 @@ final class WallPresenter extends OpenVKPresenter
(new RepostNotification($post->getOwner(false), $post, $this->user->identity))->emit();
};
exit(json_encode(["wall_owner" => $this->user->identity->getId()]));
$this->returnJson(["wall_owner" => $this->user->identity->getId()]);
}
function renderDelete(int $wall, int $post_id): void

View file

@ -38,6 +38,22 @@ function hidePanel(panel, count = 0)
}
function parseAjaxResponse(responseString) {
try {
const response = JSON.parse(responseString);
if(response.flash)
NewNotification(response.flash.title, response.flash.message || "", null);
return response.success || false;
} catch(error) {
if(responseString === "Хакеры? Интересно...") {
location.reload();
return false;
} else {
throw error;
}
}
}
document.addEventListener("DOMContentLoaded", function() { //BEGIN
@ -100,6 +116,15 @@ document.addEventListener("DOMContentLoaded", function() { //BEGIN
let req = await ky(link);
if(req.ok == false) {
NewNotification(tr('error'), tr('error_1'), null);
thisButton.nodes[0].classList.remove('loading');
thisButton.nodes[0].classList.remove('disable');
return;
}
if(!parseAjaxResponse(await req.text())) {
thisButton.nodes[0].classList.remove('loading');
thisButton.nodes[0].classList.remove('disable');
return;
}
// Adding a divider if not already there
@ -145,7 +170,7 @@ function repostPost(id, hash) {
xhr.open("POST", "/wall"+id+"/repost?hash="+hash, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = (function() {
if(xhr.responseText.indexOf("wall_owner") === -1)
if(xhr.responseText.indexOf("wall_owner") === -1)
MessageBox(tr('error'), tr('error_repost_fail'), tr('ok'), [Function.noop]);
else {
let jsonR = JSON.parse(xhr.responseText);
@ -222,4 +247,3 @@ function showCoinsTransferDialog(coinsCount, hash) {
Function.noop
]);
}