Skip to content

Categories:

How-To Create Your Own Instant Search

Google recenlty launched a new way to search the web called Google Instant, which can save several seconds per search.
Google instant involves a lot of high technology, including a new and smarter predicting system.
This technology is not available for every webmaster in your own page yet, however, we can get really good results with php and jQuery, allowing everyone to create your own version of instant search.
We are going to create now the simplest code, in order to learn how it works.
This way anyone may learn easily and recreate it, fitting it perfectly with your own project.
The following image illustrates how the instant search works.
Create a link to jQuery in the head tag of the page. Than create a simple search field using a form with an input field in a HTML page. Below the form add a layer which will contain search results.
Search results will appear immediately into the result’s container while you write a string to search into the input field using a combination of PHP and JavaScript code.
The HTML code is really simple: just a form with a layer which contains search results.
<html>
    <head>
        <title>Instant Search</title>
        <script type=”text/javascript” src=”../jquery.js”></script>
</head>
    <body>

       //Form
        <form method=”get” action=””>
            <input type=”text” id=”q” name=”q” />
            <input type=”submit” value=”Search” />
        </form>

        //Result’s Container
       <div id=”results”></div>

    </body>
</html>

Here is the JavaScript code:
<script type="text/javascript">
    var runningRequest = false;
    var request;

   //Identify the typing action
    $('input#q').keyup(function(e){
        e.preventDefault();
        var $q = $(this);

        if($q.val() == ''){
            $('div#results').html('');
            return false;
        }

        //Abort opened requests to speed it up
        if(runningRequest){
            request.abort();
        }

        runningRequest=true;
        request = $.getJSON('search.php',{
            q:$q.val()
        },function(data){           
            showResults(data,$q.val());
            runningRequest=false;
        });

//Create HTML structure for the results and insert it on the result div
function showResults(data, highlight){
           var resultHtml = '';
            $.each(data, function(i,item){
                resultHtml+='<div class="result">';
                resultHtml+='<h2><a href="#">'+item.title+'</a></h2>';
                resultHtml+='<p>'+item.post.replace(highlight, '<span class="highlight">'+highlight+'</span>')+'</p>';
                resultHtml+='<a href="#" class="readMore">Read more..</a>'
                resultHtml+='</div>';
            });

            $('div#results').html(resultHtml);
        }

        $('form').submit(function(e){
            e.preventDefault();
        });
    });
</script>

Here is the PHP code:
<?php
if(!empty($_GET['q'])) {
    search();
}

function search() {
    $con = mysql_connect('localhost','root', '');
    mysql_select_db('mydb', $con);

    $q = mysql_real_escape_string($_GET['q'], $con);
    $sql = mysql_query("
        SELECT
            p.title, SUBSTR(p.post,1,300) as post
        FROM Posts p
        WHERE p.title LIKE '%{$q}%' OR p.post LIKE '%{$q}%'
        ");

    //Create an array with the results
    $results=array();
    while($v = mysql_fetch_object($sql)){
        $results[] = array(
          'title'=>$v->title,
          'post'=>$v->post
        );
    }

    //using JSON to encode the array
    echo json_encode($results);
}

Here is an example for the CSS code:
form{
      margin:15px;
      padding:5px;
      border-bottom:1px solid #ddd;
    }

      form input[type=submit]{display:none;}

      div#results{
        padding:10px 0px 0px 15px;
       }

      div#results div.result{
           padding:10px 0px;
           margin:10px 0px 10px;
       }

      div#results div.result a.readMore{color:green;}

      div#results div.result h2{
       font-size:19px;
       margin:0px 0px 5px;
       padding:0px;
       color:#1111CC;
       font-weight:normal;
       }

      div#results div.result h2 a{
        text-decoration:none;
       border-bottom:1px solid #1111cc;
      }

      div#results div.result p{
       margin:0;
      padding:0;
}

      span.highlight{
       background:#FCFFA3;
       padding:3px;
       font-weight:bold;
}

And this is all you have to do. Note: Your project doesn’t need to have an specific page to this search. You may use CSS to hide and set absolute position to the results div. This way the instant search will work in every section!

Posted in Uncategorized.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.