ПОИСК / Рабочий поиск по сайту с Autocomplete

Заметка создана: 08 марта 2024 г.

HTML

            <form action="/search/" class="top-search-form" method="GET">
                <input  id="search" name="src" placeholder="Поиск по каталогу" type="text" value="<?=isset($_GET['src'])?$_GET['src']:''?>" />
                <input class="submitSearch" type="submit" value="" />
            </form>
Код настроек Типовой динамической страницы "Поиск"
<?php


$text = strval(Core_Array::getGet('text'));
if ($text)
{
    Core_Page::instance()->title('Поиск: ' . $text);
}


//Autocomplete
if (!is_null(Core_Array::getGet('autocomplete')) && !is_null(Core_Array::getGet('query')))
{
    //$iShopId = 1;
    $sQuery = Core_Str::stripTags(strval(Core_Array::getGet('query')));


    $aJSON = array();
    $aJSON['query'] = $sQuery;
    $aJSON['suggestions'] = array();


    $oShop_Items = Core_Entity::factory('Shop_Item');
    $oShop_Items->queryBuilder()
        ->select('shop_items.*')
        ->join('shops', 'shop_items.shop_id', '=', 'shops.id')
        ->where('shops.site_id', '=', CURRENT_SITE)
                ->where('shop_items.active', '=', 1)
                ->where('modification_id', '=', '0')
        ->where('shop_items.name', 'LIKE', '%' . $sQuery . '%')
        ->limit(50);


    $aShop_Items = $oShop_Items->findAll();


    foreach ($aShop_Items as $oShop_Item)
    {
        $aJSON['suggestions'][] = array(
            'value' => $oShop_Item->name,
            'price' => $oShop_Item->price,
            'data' => $oShop_Item->id
        );
    }


    Core_Page::instance()->response
        ->status(200)
        ->header('Pragma', "no-cache")
        ->header('Cache-Control', "private, no-cache")
        ->header('Vary', "Accept")
        ->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
        ->header('X-Powered-By', 'HostCMS')
        ->header('Content-Disposition', 'inline; filename="files.json"');


    Core_Page::instance()->response
        ->body(json_encode($aJSON))
        ->header('Content-type', 'application/json; charset=utf-8');


    Core_Page::instance()->response
        ->sendHeaders()
        ->showBody();


    exit();
}

JavaScript / jQuery

// jQuery.Autocomplete selectors
$('#search').autocomplete({
serviceUrl: '/search/?autocomplete=1',
delimiter: ',',
maxHeight: 300,
width: 300,
deferRequestBy: 300,
appendTo: '.top-search-form',
onSelect: function (suggestion) {
$(this).closest("form").submit();
}
});