Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery autocomplete server-side matching

I am trying to setup an autocomplete field.

I'v read the JQuery UI documentation, but all the example assume the source is a static list of items from which JQuery will pick matching entries (I mean static = the list is complete and doesn't depend on what the user typed).

Here is the code from the "remote datasource" example:

$( "#birds" ).autocomplete({
    source: "search.php",
    ...

I would like JQuery to call search.php?query=mytext (this URL returning a list of matching items) because I need to lookup suggestions in a database using PHP.

Is there a way to do that? Maybe I didn't understand the documentation?

like image 389
Matthieu Napoli Avatar asked Jan 15 '12 21:01

Matthieu Napoli


2 Answers

from the jQuery UI Documentation on autocomplete:

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

  • an Array with local data
  • a String, specifying a URL
  • a Callback

and further down

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.

have you tried the code you give? it should call the url search.php?term=mytext

like image 195
bjelli Avatar answered Oct 04 '22 22:10

bjelli


Here is a snippet of some client-side code I wrote a while back (changed to protect the innocent!) which does exactly as you want ...

    function ConfigureAutoComplete() {

        $('#myautocomplete').autocomplete({
            type: "POST",
            minLength: 3,
            source : function (request, response) 
            {                         
                var source_url = "../handlers/MyLookup.ashx?someparameter=" + $("#someparameter").val();

                $.ajax({
                    url: source_url,
                    dataType: "json",
                    data: request,
                    success: function (data) { response(data); },
                    error : function (a,b,c) { HandleLookUpError(a); }
                    });
            },                
            select: function (event, ui) { $('#result').val(ui.item.id); }               
        });
    }

As has already been said, your search.php page can return whatever you want it to. So you can narrow down the list on the server and return it to the client, which will then allow the user to pick from that list.

like image 21
Antony Scott Avatar answered Oct 04 '22 22:10

Antony Scott