Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery AutoComplete returning [object Object]

When using jQuery autocomplete I get [object Object] rendered below autocomplete element instead of the values from the database (click here for error screenshot.). Can someone please suggest where I am going wrong.

Here is my jQuery Mobile code

$( document ).on( "pageinit", "#myPage", function() {
    $( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
        var $ul = $( this ),
            $input = $( data.input ),
            value = $input.val(),
            html = "";
        $ul.html( "" );
        if ( value && value.length > 2 ) {
            $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
            $ul.listview( "refresh" );
            $.ajax({
                url: "/get_names/",
                dataType: "json",
                crossDomain: true,
                data: {
                    q: $input.val()
                }
            })
            .then( function ( response ) {
                $.each( response, function ( i, val ) {
                    html += "<li>" + val + "</li>";
                });
                $ul.html( html );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout");
            });
        }
    });
});

Here is my html code

<div data-role="page" id="myPage">

    <div data-role="content">

    <ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Search House Id..." data-filter-theme="d"></ul>
    </div><!-- /content -->
</div>

Here is my Django code in views.py

def get_names(request):
    q = request.GET.get('term', '')
    names = Names.objects.filter(names__startswith=q)[:10]
    results = []
    if names.count > 0:
        for name in names:
            name_json = {}
            name_json['id'] = name.id
            name_json['label'] = name.name
            name_json['value'] = name.name
            results.append(name_json)
            data = json.dumps(results)
    else:
             data = 'fail'

    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
like image 475
kurrodu Avatar asked Feb 26 '26 06:02

kurrodu


1 Answers

I am not familiar with django but if I am following correctly I think you need to change the following:

$.each( response, function ( i, val ) {
  html += "<li>" + val.value + "</li>";
});

val is an object.

Also for just a debugging tip I would add console.log(response); before the $.each(); in order to figure out what val is going to be if I were to run into a situation like you are in.

like image 80
dwaddell Avatar answered Feb 28 '26 19:02

dwaddell