Webmaster общности: Predpriemach.com | SearchEngines.bg

    jQuery търсачка с предположения

    jQuery уроци

    Автор: Lambenstein

    Това е много симпатична и много лесна за използване и създаване търсачка, тя използва база данни, с картинки, информация и имена на файлове, линкове или друг вид информация. Създаването и отнема не повече от 15 минути. Търсачката е вдъхновена от сайта на Apple. В бъдеще ще се опитам да я направя като плъгин за CMS-системи(WordPress/Joomla/Drupal т.н.).

    Преди да започнем искам да кажа, че тя използва CSS 3, и ефекта сянка зад падащото меню се поддържа за сега само от Safari, Chrome и Opera. При употреба на други браузъри този ефект няма да се показва.

    Добре нека да започваме!

    За търсачката ни трябват 2 дата бази, една, която ще съдържа информацията и втора, в която ще се поставят категориите.

    Категории:

    CREATE TABLE IF NOT EXISTS `categories` (
    `cid` int(11) NOT NULL AUTO_INCREMENT,
    `cat_name` varchar(255) NOT NULL,
    `cat_url` text NOT NULL,
    PRIMARY KEY (`cid`)
    );
    
    CREATE TABLE IF NOT EXISTS `search` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `cat_id` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    `img` varchar(255) NOT NULL,
    `desc` text NOT NULL,
    `url` text NOT NULL,
    PRIMARY KEY (`id`)
    );

    И за останалата информация(имена, линкове и др.):

    CREATE TABLE IF NOT EXISTS `search` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `cat_id` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    `img` varchar(255) NOT NULL,
    `desc` text NOT NULL,
    `url` text NOT NULL,
    PRIMARY KEY (`id`)
    );

    Добре вече запазихме информацията, сега ще преминем към Html файла.

    Страницата съдържа само формата на търсачката. Формата не съдържа .

    Eто и кода за формата:

    <div>
    <form id="searchform">
    <div>
    What are you looking for? <input type="text" size="30" value="" />
    </div>
    <div id="suggestions"></div>
    </form>
    </div>

    Преминаваме към CSS файла:

    Сега ще разкрасим формата(малко е скучно, но си заслужава):

    /* HTML ELEMENTS */
    body { font-family:"Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif;
    background-color:#efefef; background-image:url(../images/bg.jpg); }
    
    /* SEARCH FORM */
    #searchform { margin:50px 200px; font-size:18px; }
    #searchform div { color:#eeeeee; }
    #searchform div input { font-size:18px; padding:5px; width:320px; }
    #suggestions{ position: relative; left:235px; width:320px; display:none; }

    Това ни е първата част CSS файлчето. Вече страницата ни изглежда така:

    Това ни е часта от файла, в която ще създаваме вида на предположенията.

    /* SEARCHRESULTS */
    #searchresults { border-width:1px; border-color:#919191; border-style:solid; width:320px; background-color:#a0a0a0; font-size:10px; line-height:14px; }
    #searchresults a { display:block; background-color:#e4e4e4; clear:left; height:56px; text-decoration:none; }
    #searchresults a:hover { background-color:#b7b7b7; color:#ffffff; }
    #searchresults a img { float:left; padding:5px 10px; }
    #searchresults a span.searchheading { display:block; font-weight:bold; padding-top:5px; color:#191919; }
    #searchresults a:hover span.searchheading { color:#ffffff; }
    #searchresults a span { color:#555555; }
    #searchresults a:hover span { color:#f1f1f1; }
    #searchresults span.category { font-size:11px; margin:5px; display:block; color:#ffffff; }
    #searchresults span.seperator { float:right; padding-right:15px; margin-right:5px;
    background-image:url(../images/shortcuts_arrow.gif); background-repeat:no-repeat; background-position:right; }
    #searchresults span.seperator a { background-color:transparent; display:block; margin:5px; height:auto; color:#ffffff; }

    След тази по-трудна част предположенията ни изглеждат така:

    Добре вече изглежда много добре, сега е време и за PHP файла. Той се пада статичен Html файл.
    Чрез него изкарваме резултатите от дата базата:

    <p id="searchresults">
    <?php
    // PHP5 Implementation - uses MySQLi.
    // mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
    $db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
    
    if(!$db) {
    // Show error if we cannot connect.
    echo 'ERROR: Could not connect to the database.';
    } else {
    // Is there a posted query string?
    if(isset($_POST['queryString'])) {
    $queryString = $db->real_escape_string($_POST['queryString']);
    
    // Is the string length greater than 0?
    if(strlen($queryString) >0) {
    $query = $db->query("SELECT * FROM search s INNER JOIN categories c ON s.cat_id = c.cid WHERE name LIKE '%" . $queryString . "%' ORDER BY cat_id LIMIT 8");
    
    if($query) {
    // While there are results loop through them - fetching an Object.
    
    // Store the category id
    $catid = 0;
    while ($result = $query ->fetch_object()) {
    if($result->cat_id != $catid) { // check if the category changed
    echo '<span class="category">'.$result->cat_name.'</span>';
    $catid = $result->cat_id;
    }
    echo '<a href="'.$result->url.'">';
    echo '<img src="search_images/'.$result->img.'" alt="" />';
    
    $name = $result->name;
    if(strlen($name) > 35) {
    $name = substr($name, 0, 35) . "...";
    }
    echo '<span class="searchheading">'.$name.'</span>';
    
    $description = $result->desc;
    if(strlen($description) > 80) {
    $description = substr($description, 0, 80) . "...";
    }
    
    echo '<span>'.$description.'</span></a>';
    }
    echo '<span class="seperator">Nothing interesting here? Try the sitemap.</span><br class="break" />';
    } else {
    echo 'ERROR: There was a problem with the query.';
    }
    } else {
    // Dont do anything.
    } // There is a queryString.
    } else {
    echo 'There should be no direct access to this script!';
    }
    }
    ?>
    </p>

    Сега малко разяснения:
    isset($_POST[‘queryString’]) – когато PHP файла приеме POST заявка със стойност queryString. Ще създадем тази POST заявка с jQuery.
    mysqli – Създава обект от МySQLi. Трябва да смените стойностите и за да се свържете с дата базата си.
    strlen($name) > 35 – Проверява дали думата е по-дълга от 35 символа.

    Най-накрая стигаме до jQuery кода, но първо трябва да променим част от Html кода, като добавим кода отдолу към input-a:

    onkeyup="lookup(this.value);"

    А сега ще трябва да го дефинираме в jQuery кода:

    function lookup(inputString) {
    if(inputString.length == 0) {
    $('#suggestions').fadeOut(); // Hide the suggestions box
    } else {
    $.post("rpc.php", {queryString: ""+inputString+""}, function(data) { // Do an AJAX call
    $('#suggestions').fadeIn(); // Show the suggestions box
    $('#suggestions').html(data); // Fill the suggestions box
    });
    }
    }

    След всичко това трябва да имате 4 файла и 2 дата бази:

    Това са:

    1. index.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>style suggestion search</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
    <div>
    <form id="searchform">
    <div>
    What are you looking for? <input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" />
    </div>
    <div id="suggestions"></div>
    </form>
    </div>
    </body>
    </html>

    rpc.php(така трябва да ви е наименован файла)

    <p id="searchresults">
    <?php
    // PHP5 Implementation - uses MySQLi.
    // mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
    $db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
    
    if(!$db) {
    // Show error if we cannot connect.
    echo 'ERROR: Could not connect to the database.';
    } else {
    // Is there a posted query string?
    if(isset($_POST['queryString'])) {
    $queryString = $db->real_escape_string($_POST['queryString']);
    
    // Is the string length greater than 0?
    if(strlen($queryString) >0) {
    $query = $db->query("SELECT * FROM search s INNER JOIN categories c ON s.cat_id = c.cid WHERE name LIKE '%" . $queryString . "%' ORDER BY cat_id LIMIT 8");
    
    if($query) {
    // While there are results loop through them - fetching an Object.
    
    // Store the category id
    $catid = 0;
    while ($result = $query ->fetch_object()) {
    if($result->cat_id != $catid) { // check if the category changed
    echo '<span class="category">'.$result->cat_name.'</span>';
    $catid = $result->cat_id;
    }
    echo '<a href="'.$result->url.'">';
    echo '<img src="search_images/'.$result->img.'" alt="" />';
    
    $name = $result->name;
    if(strlen($name) > 35) {
    $name = substr($name, 0, 35) . "...";
    }
    echo '<span class="searchheading">'.$name.'</span>';
    
    $description = $result->desc;
    if(strlen($description) > 80) {
    $description = substr($description, 0, 80) . "...";
    }
    
    echo '<span>'.$description.'</span></a>';
    }
    echo '<span class="seperator">Nothing interesting here? Try the sitemap.</span><br class="break" />';
    } else {
    echo 'ERROR: There was a problem with the query.';
    }
    } else {
    // Dont do anything.
    } // There is a queryString.
    } else {
    echo 'There should be no direct access to this script!';
    }
    }
    ?>
    </p>

    style.css

    /* BASIC RESET */
    body, div, img, p { padding:0; margin:0; }
    a img { border:0 }
    
    /* HTML ELEMENTS */
    body { font-family:"Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif; background-color:#efefef; background-image:url(../images/bg.jpg); }
    
    /* COMMON CLASSES */
    .break { clear:both; }
    
    /* SEARCH FORM */
    #searchform { margin:50px 200px; font-size:18px; }
    #searchform div { color:#eeeeee; }
    #searchform div input { font-size:18px; padding:5px; width:320px; }
    #suggestions{ position: relative; left:235px; width:320px; display:none; }
    
    /* SEARCHRESULTS */
    #searchresults { border-width:1px; border-color:#919191; border-style:solid; width:320px; background-color:#a0a0a0; font-size:10px; line-height:14px; }
    #searchresults a { display:block; background-color:#e4e4e4; clear:left; height:56px; text-decoration:none; }
    #searchresults a:hover { background-color:#b7b7b7; color:#ffffff; }
    #searchresults a img { float:left; padding:5px 10px; }
    #searchresults a span.searchheading { display:block; font-weight:bold; padding-top:5px; color:#191919; }
    #searchresults a:hover span.searchheading { color:#ffffff; }
    #searchresults a span { color:#555555; }
    #searchresults a:hover span { color:#f1f1f1; }
    #searchresults span.category { font-size:11px; margin:5px; display:block; color:#ffffff; }
    #searchresults span.seperator { float:right; padding-right:15px; margin-right:5px;
    background-image:url(../images/shortcuts_arrow.gif); background-repeat:no-repeat; background-position:right; }
    #searchresults span.seperator a { background-color:transparent; display:block; margin:5px; height:auto; color:#ffffff; }

    script.js (така трябва да е наименован файла)

    google.load("jquery", "1.3.1");
    google.setOnLoadCallback(function()
    {
    // Safely inject CSS3 and give the search results a shadow
    var cssObj = { 'box-shadow' : '#888 5px 10px 10px', // Added when CSS3 is standard
    '-webkit-box-shadow' : '#888 5px 10px 10px', // Safari
    '-moz-box-shadow' : '#888 5px 10px 10px'}; // Firefox 3.5+
    $("#suggestions").css(cssObj);
    
    // Fade out the suggestions box when not active
    $("input").blur(function(){
    $('#suggestions').fadeOut();
    });
    });
    
    function lookup(inputString) {
    if(inputString.length == 0) {
    $('#suggestions').fadeOut(); // Hide the suggestions box
    } else {
    $.post("rpc.php", {queryString: ""+inputString+""}, function(data) { // Do an AJAX call
    $('#suggestions').fadeIn(); // Show the suggestions box
    $('#suggestions').html(data); // Fill the suggestions box
    });
    }
    }

    И 2-те дата бази ги направихме в началото на урока.

    Това е всичко! Ако имате въпроси пишете в коментарите отдолу.
    Демо видео:

    И разбира се и линк за сваляне:
    Цък!!!

    Това е първият ми урок, затова ако има някакви неточности пишете в коментарите.
    Надявам се урока да ви е бил полезен!