I'm trying to use an ajax search slice for my website that I found here: http://www.web2pyslices.com/slices/take_slice/51
But for some reason I keep getting the error:
IndexError: list index out of range
Here is my version of the code:
default.py (controller)
def index():
listings = db().select(db.listing.ALL, orderby=db.listing.first_name)
return dict(listings=listings, livesearch=livesearch())
def livesearch():
partialstr = request.vars.values()[0]
query = db.listing.title.like('%'+partialstr+'%')
listings = db(query).select(db.listing.title)
items = []
for (i,listing) in enumerate(listings):
items.append(DIV(A(listing.title, _id="res%s"%i, _href="#", _onclick="copyToBox($('#res%s').html())"%i), _id="resultLiveSearch"))
return TAG[''](*items)
livesearch.html (view, which I'm {{including}} in the layout.html
<input type="text" id="search" name="search" autocomplete="off" onkeyup="getData(this.value);" /><br />
<div id="ajaxresults"></div>
db.py (model)
db.define_table(auth.settings.table_user_name,
Field('first_name'),
Field('last_name'),
Field('email'),
Field('password','password', length=512, readable=False, label='Password'),
Field('title'),
Field('photo','upload'),
Field('bio','text'),
Field('phone'), # Contact details
Field('website'),
Field('address'),
Field('registration_key', length=512,
writable=False, readable=False, default=''),
Field('reset_password_key', length=512,
writable=False, readable=False, default=''),
Field('registration_id', length=512,
writable=False, readable=False, default=''),
)
listing = db[auth.settings.table_user_name]
Any help would be very very greatly appreciated, cause I've been wracking my brains on it for days now (because I'm extremely new to programming)
Thanks!
You don't want to return
livesearch
from theindex
function. According to the slice you referenced, thelivesearch
function should be called via Ajax from yourindex
page.I know the above line is taken directly from the slice, but a better (and more typical way) to access the value of the posted variable is:
Note, the above syntax will return
None
if there are norequest.vars
or ifrequest.vars.partialstr
doesn't exist, so it won't generate an error.Also,
request.vars
will beNone
whenever there are no request variables, so you can always test for request variables with:Finally, you may be interested in web2py's built-in auto-complete widget (though I think there may be some problems with it in IE, for which a fix is in the works).
If the following is your index() code:
then, if you visit index.html page and livesearch() will be called, but at this time, request.vars.values() is empty, so IndexError raised.
Don't call livesearch() in index(), and use ajax to post search word to livesearch.html, and web2py will call livesearch(), and request.vars.values()[0] is the search word.