jQuery JSON Autocomplete

Posted by David in Open Source, echolibre, industry, jquery, json
Saturday, June 13th, 2009 at 12:14
A number of people have asked me over the past few days how should one go about using jQuery Autocomplete but instead of using newline delimiters, with a URL that returns JSON data.

At first, I first had a hack that involved handling the “keyup” event myself then sending a request to a JSON URL, and then involve the “autocompleteArray” method from Autocomplete. It was a mess considering that the autocomplete method is already sending the value of your defined input to the server as a GET parameter. I was repeating the behavior of the function in order to receive a simple JSON array. I was unhappy, and felt it to be a very annoying solution because I wanted to take advantage of the internal caching system of jQuery Autocomplete.

So I decided to give a look at the code and came up with a much cleaner solution. I directly added a JSON option to the Autocomplete. So for anyone interested you can find the patch here: jQuery Autocomplete JSON patch.

The first step thing you’ll need is to patch Autocomplete using the patch command (Google patch) and then include the jQuery and Autocomplete JavaScript sources into your code.

1
2
3
4
5

Once you are done, you need to setup your input field on which the autocomplete calls and function is going to be executed from.

1

And of course you need to make the event hook to make sure your autocomplete is done but in the hook you need to make sure the new option “json” is set to true. This is how you proceed:

1
2
3
$(function() {
$(‘#input’).autocomplete(‘url.php’, {json: true});
});
The complete version should look somewhat like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20












You can even try it now if you want.

You can leave a response, or trackback from your own site.

Comments (8 Responses)
prasanta lahkar
July 3rd, 2009 at 15:47
This is what I was looking for. Its very impressive.

Chris
August 8th, 2009 at 18:36
Thanks. but did not work for me, as i am using cross domain.

David
September 8th, 2009 at 11:50
Actually @Chris it should. You can use the url.php script to make a request to your external domain. url.php should only behave as a proxy and you’ll be able to use any resultset from there.

Canavaro
July 15th, 2010 at 16:57
This is what I was looking for. how i pay?

auraham
March 11th, 2011 at 18:12
what is the content of url.php?

I guess that it could be:

its ok?

auraham
March 11th, 2011 at 18:12
what is the content of url.php?

I guess that it could be:

$data = array(’id’,’value’);
echo json_encode($data);

its ok?

David
March 11th, 2011 at 18:14
Check this out: http://labs.echolibre.com/jquery/autocomplete/url.phps

ankur khurana
May 12th, 2011 at 08:21
awsum thanks buddy… just what i was looking for…
great work!