From 27866d7e4f242a3be123134ca378a8ee4dc42aed Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Mon, 25 Nov 2024 01:19:18 +0100 Subject: [PATCH] Tpl::display_ajax_return(): add $keep_messages_on_success parameter --- src/Tpl.php | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/src/Tpl.php b/src/Tpl.php index 9a90fba..02ed8af 100644 --- a/src/Tpl.php +++ b/src/Tpl.php @@ -535,11 +535,17 @@ class Tpl { * Display AJAX return * @param array|null $data AJAX returned data (optional) * @param int|null $error_code HTTP error code (optional, default: 400 if not $data['success']) - * @param bool $pretty AJAX returned data + * @param bool|null $pretty AJAX returned data * (optional, default: true if $_REQUEST['pretty'] is set, False otherwise) + * @param bool $keep_messages_on_success If true and the return is a success, errors & messages + * will be keep in session and will not be included in this + * Ajax return (useful if you want to trigger redirect on + * success) * @return never */ - public static function display_ajax_return($data=null, $error_code=null, $pretty=false) { + public static function display_ajax_return( + $data=null, $error_code=null, $pretty=null, $keep_messages_on_success=false + ) { if (!is_array($data)) $data = array(); @@ -550,18 +556,25 @@ class Tpl { ) http_response_code($error_code ? $error_code : 400); - $data['messages'] = self :: get_messages(); - if (!$data['messages']) unset($data['messages']); - self :: purge_messages(); + if (($data['success'] ?? false) && !$keep_messages_on_success) { + $data['messages'] = self :: get_messages(); + if (!$data['messages']) unset($data['messages']); + self :: purge_messages(); - $data['errors'] = self :: get_errors(); - if (!$data['errors']) unset($data['errors']); - self :: purge_errors(); + $data['errors'] = self :: get_errors(); + if (!$data['errors']) unset($data['errors']); + self :: purge_errors(); + } if (self :: $_debug_ajax) Log :: debug("AJAX Response : ".vardump($data)); header('Content-Type: application/json'); - echo json_encode($data, (($pretty||isset($_REQUEST['pretty']))?JSON_PRETTY_PRINT:0)); + echo json_encode( + $data, + ($pretty ?? false) || isset($_REQUEST['pretty'])? + JSON_PRETTY_PRINT: + 0 + ); exit(); }