Added ajax search and fixed body type for request on ajax

This commit is contained in:
Stepan 2025-06-28 00:39:25 +02:00
parent b66f2c6709
commit c374c50ca0
2 changed files with 24 additions and 33 deletions

View File

@ -15,10 +15,7 @@ class AjaxController extends BaseController
require_once APPS_PATH . '/Ajax/ajax-actions.php'; require_once APPS_PATH . '/Ajax/ajax-actions.php';
$context['result'] = ""; $context['result'] = "";
$json = file_get_contents('php://input'); $action = $_POST['action'] ?? false;
$data = json_decode($json, true);
$action = $data['action'] ?? false;
// If request from other site // If request from other site
if (!in_array($_SERVER['HTTP_HOST'], ALLOWED_HOSTS)) { if (!in_array($_SERVER['HTTP_HOST'], ALLOWED_HOSTS)) {
@ -34,7 +31,7 @@ class AjaxController extends BaseController
$action = "ajax_" . $action; $action = "ajax_" . $action;
try { try {
$context['result'] = $action($data['args']); $context['result'] = $action();
} catch (\Exception $ex) { } catch (\Exception $ex) {
$context['result'] = get_ajax_error($ex->getMessage()); $context['result'] = get_ajax_error($ex->getMessage());
} }

View File

@ -1,5 +1,7 @@
<?php <?php
use Lycoreco\Apps\Recipes\Models\RecipeModel;
function get_ajax_error($message, $error_code = 500) function get_ajax_error($message, $error_code = 500)
{ {
http_response_code($error_code); http_response_code($error_code);
@ -13,35 +15,27 @@ function get_ajax_error($message, $error_code = 500)
/** /**
* Ajax actions * Ajax actions
*/ */
function ajax_search($args) { function ajax_search() {
$search_query = $args['query']; $search_query = $_POST['query'] ?? null;
if (!isset($search_query)) {
$result = []; return get_ajax_error("Missing 'query' parameter.", 400);
$data = [
[
'id' => 2,
'name' => 'Genshin Impact'
],
[
'id' => 3,
'name' => 'Zenless zone zero'
],
[
'id' => 4,
'name' => 'Honkai Star Rail'
],
[
'id' => 5,
'name' => 'Honkai Impact'
],
];
$result['results'] = [];
foreach ($data as $key => $value) {
if(str_contains($value['name'], $search_query))
$result['results'][] = $value;
} }
sleep(3); if (!CURRENT_USER) {
return get_ajax_error('You are not authorized', 401);
}
$result = array();
$recipes = RecipeModel::filter(
array(),
array(),
5,
'AND',
0,
$search_query
);
$result['count'] = count($recipes);
$result['result'] = $recipes;
return json_encode($result, JSON_PRETTY_PRINT); return json_encode($result, JSON_PRETTY_PRINT);
} }