Lelly
Lelly

Reputation: 968

jquery plugin Autocomplete - not displaying results

I'm having a problem with the Auto complete plug-in. Here is my code:

    var autocomplete = {
       cache: {},
       xhr: {}
    };

   $('#header .search input[type="text"]').autocomplete({
      minLength : 2,
      source: function (request,response) {
         var q = request.term;
         if( q in autocomplete.cache ) {
           response( autocomplete.cache[q] );
           return false;
         } else {
           autocomplete.hxr = $.getJSON("/search/autocomplete/nous?ajax=1&q="+q,function(data, status, xhr) {
           autocomplete.cache[q] = data;
           //if( autocomplete.xhr === xhr ) { 
                response(data);
           //}
        });
        return true;
        }
       }
    });

When I'm writing something in the input ("Hello" in this case), I can see in the web developer tool that its returning a json array. So, I'm getting a valid response when the request is done.

 0: "hello kitty"
 1: "hello dolly and frieda"
 2: "hello ass"
 3: "hello there"
 4: "hello do you make"

It is doing the ajax requests but the results are not being pushed into the drop-down menu, it's empty. Any help is appreciated!!

Thanks!

Upvotes: 0

Views: 175

Answers (1)

Kevin B
Kevin B

Reputation: 95062

This answer is based on comments:

This is how you could accomplish the same goal using deferred objects:

var autocomplete = {
    cache: {}
};

$('#header .search input[type="text"]').autocomplete({
    minLength: 2,
    source: function(request, response) {
        var q = request.term;
        if (!autocomplete.cache[q]) {
            autocomplete.cache[q] = $.getJSON("/search/autocomplete/nous?ajax=1&q=" + q);
        }
        autocomplete.cache[q].done(response).fail(function(x,y,z){
            alert(x.responseText + "\n-----\n" + y + "\n" + z);
        });       
    }
});

Edit: looks like the reason the original code wouldn't work was due to the typo.

Edit2: added fail handler

Upvotes: 1

Related Questions