Tpl::display_ajax_return(): add $keep_messages_on_success parameter

This commit is contained in:
Benjamin Renard 2024-11-25 01:19:18 +01:00
parent 44fc339057
commit 27866d7e4f
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -535,11 +535,17 @@ class Tpl {
* Display AJAX return * Display AJAX return
* @param array|null $data AJAX returned data (optional) * @param array|null $data AJAX returned data (optional)
* @param int|null $error_code HTTP error code (optional, default: 400 if not $data['success']) * @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) * (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 * @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)) if (!is_array($data))
$data = array(); $data = array();
@ -550,18 +556,25 @@ class Tpl {
) )
http_response_code($error_code ? $error_code : 400); http_response_code($error_code ? $error_code : 400);
$data['messages'] = self :: get_messages(); if (($data['success'] ?? false) && !$keep_messages_on_success) {
if (!$data['messages']) unset($data['messages']); $data['messages'] = self :: get_messages();
self :: purge_messages(); if (!$data['messages']) unset($data['messages']);
self :: purge_messages();
$data['errors'] = self :: get_errors(); $data['errors'] = self :: get_errors();
if (!$data['errors']) unset($data['errors']); if (!$data['errors']) unset($data['errors']);
self :: purge_errors(); self :: purge_errors();
}
if (self :: $_debug_ajax) if (self :: $_debug_ajax)
Log :: debug("AJAX Response : ".vardump($data)); Log :: debug("AJAX Response : ".vardump($data));
header('Content-Type: application/json'); 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(); exit();
} }