How to set up Realtime Autocomplete - WassifAziz/Realtime-Autocomplete GitHub Wiki

AutoComplete with Ajax database updates

Summary

Scenario :There are two fields which have autocomplete enabled(Checks a DB table). The user enters London in the first field, as soon as the user clicks the second field, the first one sends a request through Ajax to push the data to the DB.

The user types L in the second field and is recommended the word 'London'.

This allows for data to be queried in realtime to a DB without the user having to press submit.

##Getting Started The first step after setting up your Rails enviroment is to include the AutoComplete gem into your project.

Download the AutoComplete gem and follow the instructions to include it in your rails project and set it up with a field.

https://github.com/crowdint/rails3-jquery-autocomplete

###jQuery UI CSS You also need to download the jQuery UI CSS file from

http://jqueryui.com/download

(Make sure the autocomplete box is checked under Widgets.)

*= require jquery-ui-1.8.23.custom.css (depending on your version, you may need to change version numbers above)

##Setting up an onchange event To set up an onchange event add the following inside your tag autocomplete_field_tag

onchange => 'method_name()'

(method_name can be anything) Give your tag a ID

:html => {:id => 'main_input' }

it should look similar to this.

 <%= autocomplete_field_tag, '', autocomplete_attribute_controller_path, method: :post , :onchange => 'show_alert()', :html => {:id => 'main_input' }%>      

##Setting up the Ajax Call.

Setting up the Ajax call is fairly straight forward, go to your application.js file and enter the following code.

Remember to replace show_alert with your method name and to set your POST URL!

function show_alert(clicked_id) //replace with the method name you set earlier.
{
 var field_value = document.getElementById(clicked_id).value;
 var field_id = document.getElementById(clicked_id).id;
 var data = {};
 data[field_id] = field_value;
 $.ajax({
   type    : 'POST',
   url     : "/url_to_post_to", 
   data  : data,
   success : function(response) {
             },  
 });
 

}

Save your file and your done.

(This is not perfect, so if you have ideas on improving the code do let me know!)