Man always search item php i. Live search on Bitrix

From the author: hello friends. In this article, we will continue to implement live search for the site. What is live search? You come across it all the time when you are looking for something in Google or Yandex. As soon as you start typing a search query, the search engine immediately begins to offer you options, from which you just have to choose the most suitable one. Handy stuff, right? Let's try and implement something similar.

Source Files current article you can download at . You can find the first part of the article at.

So, in the first part, we prepared the database that will be used for live search, and also screwed the Autocomplete widget jQuery libraries UI to the search box on our page. So far, the widget works with test data, but now we will fix it.

First of all, let's specify another data source for the widget, it will be, say, the search.php file, which we also need to create.

$(function()( $("#search").autocomplete(( source: "search.php", )); ));

Now I'll type any character in the search field and see what happens in the browser console.

As you can see, it goes GET request with a term parameter whose value is the string typed in the search field. In this case, everything happens asynchronously, without reloading the page, i.e. using AJAX.

Great, now all that remains is to accept the incoming search query and issue an answer to it. To do this, you need to organize a connection to the database server and write a simple code that receives data from the database on request. The search.php file code will be something like this:

$db = mysqli_connect("localhost", "root", "", "world") or die("No DB connection"); mysqli_set_charset($db, "utf8") or die("Connection encoding not set"); /** * autocomplete search **/ function search_autocomplete()( global $db; $search = trim(mysqli_real_escape_string($db, $_GET["term"])); $query = "SELECT Name FROM city WHERE Name LIKE " %($search)%" LIMIT 10"; $res = mysqli_query($db, $query); $result_search = array(); while($row = mysqli_fetch_assoc($res))( $result_search = array("label" => $row["Name"]); ) return $result_search; ) if(!empty($_GET["term"]))( $search = search_autocomplete(); exit(json_encode($search)); )

$ db = mysqli_connect ("localhost" , "root" , "" , "world" ) or die ( "No database connection") ;

mysqli_set_charset($db, "utf8") or die( "Connection encoding not set") ;

* autocomplete search

function search_autocomplete()(

global $db;

$ search = trim (mysqli_real_escape_string ( $ db , $ _GET [ "term" ] ) ) ;

$res = mysqli_query($db, $query) ;

$result_search = array();

while ($row = mysqli_fetch_assoc($res) ) (

$result_search = array("label" => $row["Name"] ) ;

return $result_search;

if (! empty ($_GET [ "term" ] ) ) (

$search = search_autocomplete();

exit(json_encode($search) ) ;

Please note that the search_autocomplete function, which receives data upon request, must return this data in a certain format, it must be an array with label keys and values ​​of the cities found. After calling the function, the data needs to be converted to JSON format.

It remains to check the work of our live search. To do this, like last time, we will type only one letter - a:

Excellent! In response, we received a dozen cities in the name of which the entered letter occurs. If we continue typing the name, the list of options will change, i.e. with each letter a new AJAX request will be sent.

Main goals:

  • implement the search in such a way that after entering search query to the line, search results appeared below this line
  • the request to get the result should occur only after the end of the input of the search query

Okay, let's go!

Approximate layout of the block itself with a search string and a div-nickname where we will add search results:

Because search is available in the site header, let's add the appropriate search and styling scripts for the results:

//finish the search: $APPLICATION->AddHeadScript("/search/ajax_search.js"); $APPLICATION->AddHeadScript("/search/jquery.mCustomScrollbar.js"); $APPLICATION->SetAdditionalCSS(SITE_TEMPLATE_PATH . "/css/ajax_search.css"); $APPLICATION->SetAdditionalCSS(SITE_TEMPLATE_PATH . "/css/jquery.mCustomScrollbar.min.css");

Now let's see what is in our ajax_search.js:

Function get_result ()( //clear the search results $("#search_result").html(""); //we haven't received the search results yet - display the preloader $("#search_result").append("

"); $.ajax(( type: "POST", url: "/search/ajax_search.php", data: "q="+q, dataType: "json", success: function(json)( //clear preloader $("#search_result").html(""); $("#search_result").append(" "); // add each element json array inside a div with class="live-search" (you can use your own layout) $.each(json, function(index, element) ( $("#search_result").find(".live-search").append (" "+element.TITLE+""+element.BODY_FORMATED+""); //console.log (element.BODY_FORMATED); )); //style the scrolling $(".live-search").mCustomScrollbar(( scrollInertia: 500 )); ) )); ) var timer = 0; var q = ""; $(document).ready(function() ( $("#q").keyup(function() ( q = this.value; clearTimeout(timer); timer = setTimeout(get_result, 1000) ; )); $("#reset_live_search").click(function() ( $("#search_result").html(""); )); ));

keyup function, we call the get_result () function, which actually fills in the div-nick with id = "search_result" in ajax.

mCustomScrollbar is just a styling call (you can turn it off).

We receive data from /search/ajax_search.php in JSON format.

Everything is clear with the JS component, now let's see what happens in ajax_search.php:

Search(array("QUERY" => $q, "SITE_ID" => LANG, "MODULE_ID" => "iblock", "CHECK_DATES" => "Y", "PARAM2" => "8")); $result = array(); while ($res = $obSearch->GetNext())( $id = $res["ITEM_ID"]; //if found section: if (strripos($id, "S")!==false)( $result_item ["TITLE"] = $res["TITLE"]; $result_item["URL"] = $res["URL"]; $result_item["BODY_FORMATED"] = $res["TITLE_FORMATED"]; $result = $ result_item; ) //if there is no S, then else( $result_item["TITLE"] = $res["TITLE"]; $result_item["URL"] = $res["URL"]; $result_item[" BODY_FORMATED"] = $res["BODY_FORMATED"]; $result = $result_item; ) ) echo json_encode($result); ) ?>

In this case, the search is performed by the Search method of the Bitrix CSearch class. In PARAM2 we write in which infoblock we are looking for. We push the search results into the $result array. Note that $res['ITEM_ID'] can be either an item or a section. Depending on what we found, in $result_item['BODY_FORMATED'] we shove either the name of the section, or a piece of text from the found element of the infoblock.

The best way to keep a user on the site is to let him find what he is looking for. If you make a convenient system for this, then the level of preference for your site will grow and the user will definitely return in order to find what interests him.

I will show you how to create a simple, but functional, search form that will be used to search for articles on the site. The results will appear on the page without any reloads, which is undoubtedly the best way submission of information.

I will create 2 files: search.php which will contain HTML and JavaScript. The second file, do_search.php will contain the PHP code. Let's start creating the first file:

PHP, jQuery search demo

Try to enter the word ajax


Results for

In this file, we have created the usual HTML form which sends POST request in the back end - to the do_search.php file.

select_list($sql); if(count($row)) ( $end_result = ""; foreach($row as $r) ( $result = $r["title"]; $bold = " " . $word . ""; $end_result .= "

  • " .str_ireplace($word, $bold, $result) . "
  • "; ) echo $end_result; ) else ( echo "
  • Nothing found for your request
  • "; } } ?>

    The PHP code contains comments that make it easy for you to understand how the script works. If there are matches in the database, you show them to your user by bolding the words the user was looking for.

    Let's give it all some CSS:

    Body( font-family:Arial, Helvetica, sans-serif; ) *( margin:0;padding:0; ) #container ( margin: 0 auto; width: 600px; ) a ( color:#DF3D82; text-decoration: none ) a:hover ( color:#DF3D82; text-decoration:underline; ) ul.update ( list-style:none;font-size:1.1em; margin-top:10px ) ul.update li( height:30px; border-bottom:#dedede solid 1px; text-align:left;) ul.update li:first-child( border-top:#dedede solid 1px; height:30px; text-align:left; ) #flash ( margin- top:20px; text-align:left; ) #searchresults ( text-align:left; margin-top:20px; display:none; font-family:Arial, Helvetica, sans-serif; font-size:16px; color: #000; ) .word ( font-weight:bold; color:#000000; ) #search_box ( padding:4px; border:solid 1px #666666; width:300px; height:30px; font-size:18px;-moz- border-radius: 6px;-webkit-border-radius: 6px; ) .search_button ( border:#000000 solid 1px; padding: 6px; color:#000; font-weight:bold; font-size:16px;-moz- border-radius: 6px;-webkit-border-radius: 6px; ) .found ( font-weight: bold ; font-style: italic; color: #ff0000; ) h2 ( margin-right: 70px; )

    So you have learned how to create a simple search form that works without reloading the page. I hope you enjoyed the lesson.

    A computer