« Apple kills third party accessories with new iPods | Main | Rove Expects to be Indicted Shortly »

Source code for CommonTimes "AJAX" Live Search

You can check out our "Live Search" feature on CommonTimes or CommonBits. Live Search allows you to search our database and see results immediately without a browser refresh.

It was written by our programming intern Garrett Moon with help from Brian at Hybernaut. If you benefit from the source code below, please donate to our intern programming fund for CommonMedia.

Below is a basic overview of the code we used for the live AJAX search:

Home Page
   require_once ('classes/live_search.php');
    echo ('<script language="javascript" src="scripts/live_search.js"></script>');
    echo ('<script>//element = document.getElementById (\'search_query\');
    function start_script ()
    {
        element = document.getElementById (\'search_query\');
        element.focus();
        crossPlatAddListener(element, "keydown", keyHandler, true);
    }</script>');
        echo ('<form name="live_search"><h2 class="today" style="font-size:14px;text-align:center;">Live Search</span></h2><input style="width:100%;" type="text" id="search_query"  value=""><div id="live_search_results" class="hidden"></div></form>');

Style Sheet CSS
.hidden
{
    visibility: collapse;
    height: 0px;
    width: 0px;
    overflow: hidden;
}

.visible
{
    visibility: visible;

}

#live_search_results

{text-align:left; font-size:10px; padding: 2px 3px 0px 2px; border:1px #039 dotted; background:#eee; }

.ls_item
{
    overflow:hidden;
    padding-bottom: 4px;
}

Javascript - scripts/live_search.js
function crossPlatAddListener(node, event, handler, stopProp)
{
  if (node.addEventListener)  // DOM Level 2
  {
    node.addEventListener(event, handler, true);
  } else {
    if (node.attachEvent)   // IE 5+
    {
      node.attachEvent("on"+name, handler);
    }
  }
}

function keyHandler (e)
{
    var retcode = true;
    var keyCode = null;
    var target = null;
   
    if (!e) e = window.event;
    if (!e) return true;
   
    if (navigator.appName == "Microsoft Internet Explorer")
    {
    keyCode = e.keyCode;
    target = e.srcElement.type;
    } else {
    keyCode = e.which;
    target = e.target.type;
    }
   
    // now do whatever you like with keyCode and target
   
    element = document.getElementById ('search_query');
    self.setTimeout('submit_search (element.value)', 100);
   
    return retcode;
}

function submit_search(search_query)
{
   
    if (search_query.length > 0)
    {
        var agt = navigator.userAgent.toLowerCase();
        var is_ie = (agt.indexOf('msie') != -1);
        var is_ie5 = (agt.indexOf('msie 5') != -1);
       
        element = document.getElementById ('live_search_results');
        element.className = "visible";
        function handle_do_search ()
        {
            if (xmlhttp.readyState == 4)//request completed
            {
                if (xmlhttp.status == 200)//request successful
                {
                    element.innerHTML = xmlhttp.responseText;
                }
                else
                {
                    //alert ('request failed');
                }
            }
        }
       
        var xmlhttp = null;
        if (is_ie)
        {
            var control = (is_ie5) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";
            try
            {
                xmlhttp = new ActiveXObject(control);
                xmlhttp.onreadystatechange = handle_do_search;
            } catch(e)
            {
                alert("You need to enable active scripting and activeX controls");
            }
        }
        else
        {
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onload = handle_do_search;
            xmlhttp.onerror = handle_do_search;
        }
       
        xmlhttp.open('GET', "classes/live_search.php?xmlRequest=true&mode=do_search&query="+ search_query +"", true);
        xmlhttp.send(null);
    }
    else
    {
        element = document.getElementById ('live_search_results');
        element.innerHTML = '';       
        element.className = "hidden";
    }
}

AJAX Query - classes/live_search.php
<?php

    if (isset ($_GET['xmlRequest']) && $_GET['xmlRequest'] == true)
    {
        if (isset ($_GET['query']))
        {
            $search_query = $_GET['query'];
        }
        else
        {
            $query = '';
        }
        if (isset ($_GET['mode']))
        {
            header ("Cache-Control: no-cache, no-store;");
            switch ($_GET['mode'])
            {
                case 'do_search':
                    echo (build_search ($search_query, 10));
                    break;
            }
        }
    }
   
    //returns the contents of a div (no div tag) containing headlines and tags that matched a search.
    function build_search ($tag_search, $num_headlines=10)
    {
        global $siteid;
        $output = '';
        $result=mysql_query( "SELECT distinct(Content.contentid), Content.title, Content.webpage FROM Content WHERE Content.title REGEXP '$tag_search' AND Content.isconfirmed=1 AND Content.siteid = $siteid ORDER BY Content.contentid desc LIMIT $num_headlines");
        while ($data = mysql_fetch_object ($result))
        {
            if (strlen ($data->title) > 60)
            {
                $data->title = substr ($data->title, 0, 57);
                $data->title .= '...';
            }
            $output .= '<div class="ls_item"><a href="'. $data->webpage .'" target="_cts">'. $data->title .'</a></div>';
        }
        return ($output);
    }
?>

If you benefit from this source code below, please donate to our intern programming fund for CommonMedia.

Comments

Steven H

Don't forget the

onLoad="if (self.start_script) start_script ();"

in your body tag.

- Steven

RonHoward

Any ideas on how I can get two (or more) of these forms working on the same page?

pete

Is this working in IE6?

Sergeus

Is this working in IE or Opera?

MRT

Hello,

Working perfect!

Thanks.

Lalicsiga

Hello, great code!
Thank! :)

Post a comment

Comments are moderated, and will not appear on this weblog until the author has approved them.

If you have a TypeKey or TypePad account, please Sign In.