views:

149

answers:

2

Here's my issue : using an autocomplete jQuery plugin, I'd like to avoid multiple ajax requests when user strikes his keynoard by surrounding the

$('#query1').autocomplete({
                    serviceUrl:'/actions/autocomplete?population=salon',
                    minChars:3, 
                    maxHeight:300,
                    width:200,
                    clearCache:true,
                    onSelect: function(suggestions,data){ $(".btn1").attr("href", "${pageContext.request.contextPath}/actions/espaceClients?participantId=" + data) }
                });

with something like

                var search = false;
            $('#query1, #query2, #query3').keyup(function(){
                if (!search){
                    search = true;
                }
                if (search) {
                    search = false;
                    autocompleteThem();
                }
            });

A you can see, above code is stupid, but it kinda shows what i'm trying to do.

In simple words, if user dosen't type anything else in a certain period of time, then you can call autocomplete.

I hope i'm being clear, as my brains are a mess...

+2  A: 

Do you really want to prevent multiple simultanious requests? This will inhibit the usefulness of this plugin. You can either add a delay to the request, or use a plugin such as AjaxQueue to ensure the results come back to the browser in the right order.

To use the built-in delay parameter (from the manual):

The delay in milliseconds the Autocomplete waits after a keystroke to activate itself. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive.

Initialize a autocomplete with the delay option specified.

$( ".selector" ).autocomplete({ delay: 0 });

Get or set the delay option, after init.

//getter
var delay = $( ".selector" ).autocomplete( "option", "delay" );
//setter
$( ".selector" ).autocomplete( "option", "delay", 0 );

The equivalent of the delay parameter for the autocomplete plugin you're using is

deferRequestBy
Andy
I'm sorry, I forgot to mention I'm using an external plugin : http://www.devbridge.com/projects/autocomplete/jquery/
pixelboy
+1  A: 

Use the deferRequestBy option on that plugin, like this:

$('#query1').autocomplete({
                serviceUrl:'/actions/autocomplete?population=salon',
                minChars:3, 
                maxHeight:300,
                width:200,
                clearCache:true,
                deferRequestBy: 200, //200ms
                onSelect: function(suggestions,data){ $(".btn1").attr("href", "${pageContext.request.contextPath}/actions/espaceClients?participantId=" + data) }
            });
Nick Craver
i'm am such crap sometimes...
pixelboy