tito_santana
tito_santana

Reputation: 41

Jquery autocomplete post request only once

I am using jquery autocomplete. I am not happy with the code below because there must be a better way to do this. (code works)

  1. I want the user to enter 3 letters into the search box
  2. autocomplete post parameters and server responds
  3. After we have the data coming from server there is no reason to post again. note: autocomplete will keep on postind data every time user adds a new letter
  4. since I have the data, I want to use this data as source of autocomplete

The code below works with a little problem. on select one it is display in the box. When I use backspace it doesnt refresh/populate the suggestions.

Question: How can I use autocomplete to post only once and reuse the response adn the source for the autocomplete?

If can anyone suggest or point any document I could read.

Thanks


jquery-1.9.1.min.js
jquery-ui-1.10.0/jquery-ui.js

     $("#birds").autocomplete
    ({
    source: function(request, response) {
    $.ajax(
    {
    url: "page.aspx",
    data: {
    Para: request.term,
    GroupID: 11,
    rGUI: 'd9',
    rURL: 'domain.com/',
    task: 'get Stuff'
    },
    type: "POST",  
    dataType: "json",  
    success: function(data) {

    //response: function(item) {
    var arr = $.map(data, function(item) {
    return {
    label: item.LN60,
    value: item.LN60,
    NDC: item.NDC
    }
    });

    $("#birds").autocomplete({
    source: arr,
    minLength: 1
    });

    $("#birds").autocomplete({
    close: function(event, ui) {
    suggestDrugs_Request();
    }
    });

    }
    });
    },
    minLength: 2,
    select: function(event, ui) {
    log(ui.item ? "Selected: " + ui.item.value + 
    " aka " + ui.item.NDC : "Nothing selected, input was "
     + this.value);
    }
    });

Upvotes: 2

Views: 4125

Answers (2)

Brian Vanderbusch
Brian Vanderbusch

Reputation: 3339

What you should do instead of adding the ajax call to the source property of the autocomplete, is add the autocomplete functioniality to the callback of the ajax call:

$.ajax({
//all your other call settings
 success: function(data){
  //init autocomplete
  $('#birds').autocomplete({
       source: data,
       //all your other autocomplete settings
  });
 }
});

Upvotes: 4

Micah
Micah

Reputation: 10395

Make the $.ajax request and bind your autocompletes (make the .autocomplete functioncalls) inside of the success: function(data) { function.

Then set the autocompletes' sources to the data that was returned (which is obviously static now)

Upvotes: 1

Related Questions