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,8 +39,19 @@ abstract class OpenVKPresenter extends SimplePresenter
Session::i()->set("_tempTheme", $theme); 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
{ {
if($json) {
$this->returnJson([
"success" => $type !== "err",
"flash" => [
"type" => $type,
"title" => $title,
"message" => $message,
"code" => $code,
],
]);
} else {
$this->flash($type, $title, $message, $code); $this->flash($type, $title, $message, $code);
$referer = $_SERVER["HTTP_REFERER"] ?? "/"; $referer = $_SERVER["HTTP_REFERER"] ?? "/";
@ -48,6 +59,7 @@ abstract class OpenVKPresenter extends SimplePresenter
header("Location: $referer"); header("Location: $referer");
exit; exit;
} }
}
protected function logInUserWithToken(): void protected function logInUserWithToken(): void
{ {
@ -120,7 +132,7 @@ abstract class OpenVKPresenter extends SimplePresenter
$this->flashFail("err", tr("captcha_error"), tr("captcha_error_comment")); $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); $ip = (new IPs)->get(CONNECTING_IP);
$res = $ip->rateLimit(); $res = $ip->rateLimit();
@ -131,7 +143,7 @@ abstract class OpenVKPresenter extends SimplePresenter
exit("Хакеры? Интересно..."); 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); 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(); $this->notFound();
if(!$club->canBeModifiedBy($this->user->identity ?? NULL)) if(!$club->canBeModifiedBy($this->user->identity ?? NULL))
$this->flashFail("err", "Ошибка доступа", "У вас недостаточно прав, чтобы изменять этот ресурс."); $this->flashFail("err", "Ошибка доступа", "У вас недостаточно прав, чтобы изменять этот ресурс.", NULL, true);
$isClubPinned = $this->user->identity->isClubPinned($club); $isClubPinned = $this->user->identity->isClubPinned($club);
if(!$isClubPinned && $this->user->identity->getPinnedClubCount() > 10) 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()) { if($club->getOwner()->getId() === $this->user->identity->getId()) {
$club->setOwner_Club_Pinned(!$isClubPinned); $club->setOwner_Club_Pinned(!$isClubPinned);
@ -118,10 +118,9 @@ final class UserPresenter extends OpenVKPresenter
} }
} }
if($isClubPinned) $this->returnJson([
$this->flashFail("succ", "Операция успешна", "Группа " . $club->getName() . " была успешно удалена из левого меню"); "success" => true
else ]);
$this->flashFail("succ", "Операция успешна", "Группа " . $club->getName() . " была успешно добавлена в левое меню");
} }
function renderEdit(): void function renderEdit(): void

View file

@ -320,7 +320,7 @@ final class WallPresenter extends OpenVKPresenter
(new RepostNotification($post->getOwner(false), $post, $this->user->identity))->emit(); (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 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 document.addEventListener("DOMContentLoaded", function() { //BEGIN
@ -100,6 +116,15 @@ document.addEventListener("DOMContentLoaded", function() { //BEGIN
let req = await ky(link); let req = await ky(link);
if(req.ok == false) { if(req.ok == false) {
NewNotification(tr('error'), tr('error_1'), null); 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 // Adding a divider if not already there
@ -222,4 +247,3 @@ function showCoinsTransferDialog(coinsCount, hash) {
Function.noop Function.noop
]); ]);
} }