Search code examples
jquerydjangoautocompletedjango-haystack

Django Haystack autocomplete jquery formatting


I'm a bit confused with the formatting of the data, I tried the documentation, both JQuery and Haystack with no luck.

I have already setup autocomplete, and when I type:

autocomplete/?search=foo

The result is:

{"results": ["foo1", "foo2", "foo3", "foo4", "foo5"]}

When I try to retrieve this and use it as source for JQuery autocomplete like so:

$('#autocomplete').autocomplete({ 
    source: function (request, response) { 
        $.getJSON("/autocomplete/?search=" + request.term, function (data) { 
            response(data); 
        }); 
    } 
});

No result is shown.

If I create a variable like so:

x = ["foo1", "foo2", "foo3", "foo4", "foo5"];

and then call it like so:

$("#autocomplete").autocomplete({
    source: x,
});

It works perfectly fine.

To be clear, I understand that results from Haystack is the variable name, just like x. The problem is, I can't seem to get it to work with JQuery. I looked at many questions in SO but couldn't find a solution.

Looking for some direction.


Solution

  • After few hours of checking debugger, confirming that data was correctly sent etc etc.. I managed to find a solution, and it was quiet simple.

    I had to store the values in an array before returning it to JQuery autocomplete function.

    Basically:

    $('#autocomplete').autocomplete({
     source: function (request, response) {
         $.getJSON("/autocomplete/?search=" + request.term,
         function (data) {
             var array = new Array();
    
             response($.map(data, function (value, key) {
                 array = value;
                 return array;
             }));
         });
     },
     minLength: 1,
    });
    

    I still don't understand why, but I'm guessing Django returns a dictionary by the looks of it, rather than a simple array or list. A Dict has key and value, so we need to get the value (in my case) and place it in an array for it to work as correct input for autocorrect.