If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

I have been learning web2py moving from PHP and built an Ajax Live Search using Python(web2py) and JQuery.

WATCH THE VIDEO TUTORIAL ON YOUTUBE HERE : http://www.youtube.com/watch?v=jGuW43sdv6E

It's very simple, easy to use and easy to code, but i hope it helps somebody ... i discuss a more complex version of this on the web2py google group were thanks to Massimo Di Pierro im using an elegant way to return the html divs! ;-)

alt text

On the view (index.html)

#

Please Note : all the CSS and JS are on the same file beacuse its easier for me to expose it here

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Ajax Live Search with web2py by Martin Sagastume</title>
    <style type="text/css">
    <!--
    #ajaxresults{
        background: #ffffff;
        padding: 5px 10px;
        max-height: 400px;
        overflow: auto;
        position: absolute;
        z-index: 99;
        border: 1px solid #A9A9A9;
        border-width: 0 1px 1px 1px;
        -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.3);
        -moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.3);
        -box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.3);
    }
    #ajaxresults a{
        color:#666666;
    }
    input[type=text]{
        font-size:12px;
        color:#666666;
        background-color:#ffffff;
        padding-top:5px;
        width:200px;
        height:20px;
        border:1px solid #999999;
    }
    //-->
    </style>
    <script type="text/javascript" src="{{=URL(r=request,c='static',f='jquery.js')}}"></script>
    <script type="text/javascript">
    jQuery(document).ready(function(){
        hide();
    });

    function getData(value){
        if(value != ""){
            $("#ajaxresults").show();
            $.post("{{=URL(r=request,f='ajaxlivesearch')}}",{partialstr:value},function(result){
                $("#ajaxresults").html(result);
            });
        }else{
            hide();
        }
    }

    function hide(){
        $("#ajaxresults").hide();
    }

    function copyToBox(value){
        $("#country").val(value);
        hide();
    }   
    </script>
</head>
<body>
    <label for="country">Search country:</label><br />
    <input type="text" id="country" name="country" autocomplete="off" onkeyup="getData(this.value);" /><br />
    <div id="ajaxresults"></div>
</body>
</html>

On the controller (Default.py)

#
# -*- coding: utf-8 -*- 
def index():
    return dict()

def ajaxlivesearch():
    partialstr = request.vars.values()[0]
    query = db.country.printable_name.like('%'+partialstr+'%')
    countries = db(query).select(db.country.printable_name)
    items = []
    for (i,country) in enumerate(countries):
        items.append(DIV(A(country.printable_name, _id="res%s"%i, _href="#", _onclick="copyToBox($('#res%s').html())"%i), _id="resultLiveSearch"))

    return TAG[''](*items)

On the model (db.py)

#

Please Note : Im using a SQLite Manage and using an SQL script to create the table, so i will just define the basic structure here and below you will see the SQL for the country table ;-)

db = DAL('sqlite://storage.sqlite')

db.define_table('country',
                Field('iso'),
                Field('name'),
                Field('printable_name'),
                Field('iso3'),
                Field('numcode'))

SQL country Table grabbed from : http://snipplr.com/view.php?codeview&id=6636

#

Please Note: Im just adding some countries not all of them, to keep it short and simple.

CREATE TABLE IF NOT EXISTS country (
  iso CHAR(2) NOT NULL PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  printable_name VARCHAR(80) NOT NULL,
  iso3 CHAR(3),
  numcode SMALLINT
);

INSERT INTO country VALUES ('UY','URUGUAY','Uruguay','URY','858');
INSERT INTO country VALUES ('UZ','UZBEKISTAN','Uzbekistan','UZB','860');
INSERT INTO country VALUES ('VU','VANUATU','Vanuatu','VUT','548');
INSERT INTO country VALUES ('VE','VENEZUELA','Venezuela','VEN','862');
INSERT INTO country VALUES ('VN','VIET NAM','Viet Nam','VNM','704');
INSERT INTO country VALUES ('VG','VIRGIN ISLANDS, BRITISH','Virgin Islands, British','VGB','092');
INSERT INTO country VALUES ('VI','VIRGIN ISLANDS, U.S.','Virgin Islands, U.s.','VIR','850');
INSERT INTO country VALUES ('WF','WALLIS AND FUTUNA','Wallis and Futuna','WLF','876');
INSERT INTO country VALUES ('EH','WESTERN SAHARA','Western Sahara','ESH','732');
INSERT INTO country VALUES ('YE','YEMEN','Yemen','YEM','887');
INSERT INTO country VALUES ('ZM','ZAMBIA','Zambia','ZMB','894');
INSERT INTO country VALUES ('ZW','ZIMBABWE','Zimbabwe','ZWE','716');

Related slices

Comments (5)

  • Login to post



  • 0
    iiit123 14 years ago
    it gets hanged when the database is huge...like around 9000 entries. cn anything be done to improve the speed ?

  • 0
    newnomad 14 years ago
    Would this work on GAE? How is it different from this widget or the one included here

  • 0
    select 14 years ago
    thanks i was wating for this, since i was too lazy to read into it myself, and it is nice that it needs not extra jquery plugin if you want to find close matches (grmnay -> germany) instead of substrings (erma -> germany) you could add something like all_items = cache.ram( 'alltitles', lambda: dict( [(x.printable_name.lower(), x.id ) for x in db(dbcountry.id>0).select()]), time_expire=60) filtered_close = difflib.get_close_matches(query,all_items) for (i,country) in enumerate([db.country[all_items[t]] for t in filtered_close]): well somehting along the lines but i guess you get the idea

  • 0
    mandriluy 14 years ago
    @select: that tip was cool... its a very interesting implementation you did here in the comments and it could be very useful for somebody who needs even a better live search with close matches, thanks for sharing ;-)

  • 0
    mandriluy 14 years ago
    Btw, this is my first screencast in English! my native language is Spanish and i was quite nervous while i did it lol ... i hope is not too bad, i want to know some english native speakers opinion! i did my best so if you consider the video was good.. rate it at youtube.

Hosting graciously provided by:
Python Anywhere