Matt Elhotiby
Matt Elhotiby

Reputation: 44086

Going from Javascript to a rails action

I currently have a city that someone will enter into the system and I want to go from my javascript action to a rails action so i can get the city.id from the database. For example

my javascript

function get_city(city){
   //city comes in like "Washington DC"
}

my rails action

def return_city_id
  @city = City.find_by_name(params["name"])
  return @city.id
end

Upvotes: 0

Views: 573

Answers (2)

Daniel O'Hara
Daniel O'Hara

Reputation: 13438

You have to use AJAX to call any methods on the server-side.

function get_city(city){
    $.getJSON("/ajax/city_id", { "city" : city }, function(data)
    {
        //Do something with data
    });
}

/ajax/city_id is some action in some controller that returns JSON when you call it.

Upvotes: 0

Nikita Rybak
Nikita Rybak

Reputation: 68046

Try ajax. You can setup path in routes.rb like find_city_id_by_name?name=Washington DC. Then you can use jquery to send request.

$.ajax({
  url: 'find_city_id_by_name',
  data: {'name' : city},
  dataType: 'text',
  success: function(id) {
    alert(id);
  }
});

In controller, you'll need to write single id as request response:

render :text => id

More information:
http://api.jquery.com/jQuery.ajax/

Although what you ask is definitely doable, querying back-end each time you need to fetch city id by its name sounds like a bad idea to me. If the name itself come from back-end (for example, you have list of cities for user to choose from), it's better to provide ids together with names (not visible to user, but somewhere in html).

Upvotes: 2

Related Questions