How to implement Drupal AJAX Autocomplete
Posted on: Monday, March 2nd 2009 by Sae Obayashi

AJAX helps you create better, faster and more user-friendly web applications with its Javascript and HTTP base. It allows the page content to be updated without reloading a whole page.

In Drupal, AJAX functionality is provided through functions in the Javasript file drupal.js, and some AJAX functions are supported by Drupal core.

I am going to explain the autocomplete which is one of the AJAX functions implemented in Drupal. When users type into a text filed, new data from the server is dynamically loaded and displayed as a list of matching options. Exchanging data beteween client and server, and updating the content are handled by the autocomplete.js. The textfield type form input has the #autocomplete_path attribute which is the path that the AJAX autocomplete script uses as the source for autocompletion. You can easily implement the AJAX autocomplete to your form using the #autocomplete_path attribute.

Implementing the autocomplete contains two parts:1) a form input textfield and 2) a handler function to parse the request and return a response. There are build-in autocomplete handler functions such as user_autocomplete() and taxonomy_autocomplete().

Here is a simple example of how to implement the autocomplete uisng the user_autocomplete() function.

function example_form(){  
  $form['item'] = array(   
    '#type' => 'textfield',   
    '#autocomplete_path' => 'user/autocomplete'  
    ); 
  }

 

This user/autocomplete path calls the user_autocomplete() function and loads matching user names.

Also, you can create a custom autocomplete handler to meet a need for your site. Let’s say you have a text field which asks users to select a node item on the site.

function example_form(){  
  $form['item'] = array(   
    '#type' => 'textfield',   
    '#autocomplete_path' => 'example/autocomplete' 
    ); 
  }

function example_menu($may_cache) {  
  $item[] = array(   
    'path' => 'example/autocomplete',   
    'callback' => 'example_autocomplete',   
    'access' => user_access('access example autocomplete')  
    ); 
  }

function example_autocomplete($string){
  $items = array();  
  $result = db_query("SELECT nid, title FROM {node} WHERE status = 1 AND title LIKE ''%s%%', $string");
  
  while($obj = db_fetch_object($result)) {
    $items[$obj->nid] = check_plain($obj->title);
  }
  print drupal_to_js($items); 
  exit();
}

 

User input is passed from the parameter and the array of matching items is printed as the response. Note that you need to escape the node titles using check_plain() because the values are HTML.

Also note that you need to use your autocomplete handler callback has proper access permission.It might be exposing some sensitive information on the site.

Comments

Thank You for this article,this was useful to me.

Thank you very much buddy. I really need this thing to implement on my site's search box. This is very help to me :).

God Bless You

I think you have a typo in your query string. the quotes extend past the $string param.

Otherwise, very helpful article, thanks!

Thanks,
Your howto was very useful, and used as the basis to my solution.
See details here - http://drupal.org/node/578620#comment-2750454

Regards,
Shushu

I know it adds a little complexity, but the query string should first be wrapped by the db_rewrite_sql function, so that the results respect any permissions settings that might prevent a user from seeing certain nodes.

So:
$result = db_query(db_rewrite_sql("SELECT..."));

very very helpful article
Thanks Sae

Hi,
Thanks for the Above functionality. Its working fine in FF3 with Scroll bar. When i tried in other browsers autocomplete scrollbar is not working. Its disappearing. Can u pls do the needful.

Thank,
Sree

Hey,
I had a query.
when the user selects the id is displayed and not title.
How did u manage that?

Thanks,
Jamir

Would you please supply for multiple input separated by commas? I want to make user tags, where the author can input more than one username into the autocomplete input separated by commas.

Thank you very much.

I'm not sure when or how this changed (Drupal 6); but I couldn't get your example to work exactly as stated.

If you update the "menu" indexes for "callback" and "access", to "page callback", and "access arguments", it works correctly.

I do not know where i put this code is it in the page body and it is working. I new thanks

Thank you, it's really good thing, but what exactly happened when add '#autocomplete_path' => 'example/autocomplete' ??

i try to add autocomplete functionality for field in multigroup (cck 3), but simply code:

$form['field_text'][0]['#autocomplete_path'] ='match_my_text';
//in hook_form_alter

does not work. Hope you help

very helpfull !! thank you \o/

Thank you very much for your post. I have a problem with this, when I select an entry from the drop down list, the nid (instead of the node title) is placed in the textfield. How can I prevent this?
Thanks,
Mike

I've added an autocomplete feature to an element loaded with ahah, but with no success.
Any suggestion ?

Post new comment

The content of this field is kept private and will not be shown publicly.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.