Search code examples
web2py

web2py: Ajax callback search functional as a Component (LOAD)


I want to include in a views/div a search functionality as a component for the reason of reusing it in different views. For that purpose I'm using a search with a ajax-callback-generated result list similar to the wiki page search described in the reference manual.

# for standalone search
# @auth.requires_login()
# for seach as a component
@auth.requires_signature()
def search():
    model_id = request.args(0,cast=int)
    form = FORM(T('Node Criteria: '), INPUT(_id='keyword',_name='keyword',
                                                        _onkeyup="ajax('callback', ['keyword'], 'nodes_in_model_result_div');"))

    # for standalone search
    # target_div =DIV(_id='nodes_in_model_result_div')

    return dict(form=form) #, target_div=target_div)


def callback():
    if (request.vars.keyword==''):
        query = db.node.title
    else:
        query = db.node.title.contains(request.vars.keyword)

    nodes = db(query).select(db.node.id, db.node.title, orderby=db.node.title)
    table = [TR(node.id, node.title) for node in nodes]

    return TABLE(THEAD(TR(TH('Node ID', _width="30%"), TH('Node'), _height="5")),
             TBODY(*table),
             _class='table table-bordered table-striped', _cellspacing="0", _width="100%", _id='nodes_in_model_table')

Everything works fine when the search is used standalone (serach.html). But as a component (search.load) embedded via LOAD() as follows the search doesn't work:

{{=LOAD('default','search.load', args=[model_id], target='nodes_in_model_div', ajax=True, user_signature=True)}}

The relevant DIVs are then defined in the calling view. The search.load only consists of {{=form}}, where the search.html is as follows:

{{extend 'layout.html'}}
<h1>Search Node</h1>
{{=form}}
<br>
{{=target_div}}

Does anybody knows how to embed a functionality using Ajax callbacks by itself in a web2py component?

Regards Clemens


Solution

  • Unfortunately, there is an error in the book example.

    _onkeyup="ajax('callback', ['keyword'], 'nodes_in_model_result_div');"
    

    In your code above, 'callback' is a relative URL, so it is appended to the URL of the parent page. Instead, you must provide the full URL path, which you should do with the URL() helper:

    _onkeyup="ajax('%s', ['keyword'], 'nodes_in_model_result_div');" % URL('default', 'callback')
    

    In the rendered HTML, that will look like:

    onkeyup="ajax('/default/callback', ['keyword'], 'nodes_in_model_result_div');"