user1510412
user1510412

Reputation: 133

rails & jquery, onchange selection auto filling input box

I am working on rails and jquery. I have a selection box called attribute. I wanted to auto fill an input field upon the attribute changes. But if I make an ajax call to a rails function, how does it both redirect back and return the value I want? The code looks like this:

function fnGetValue() {
  return $.get(
    "/get_value",
    {attribute: attr}
  );
}

$(document).ready(function() {
  $("#attribute").change(function(event) {
    fnGetValue().done(function(result) {
      $("#value").val(result);
    });
  });
});

def get_value
  ret = get_from_db
  return ret
  #redirect_to :back
end

Upvotes: 0

Views: 585

Answers (1)

Micka
Micka

Reputation: 1834

The problem is in your ruby code. return ret doesn't send the ret value back to your browser.

To do so you should use render.

def get_value
  ret = get_from_db
  render json: {data:ret}
end

UPDATE

Json is the way to share data between Javascript and any other technology.
It can be an array ([val1, val2]), or a dictionary ({key:value, key2:value2}).
So in your .done Javascript method result is expected to be either an array or a dictionary.

I believe get_from_db return arrays, dictionaries or even string and integer.
So to make sure your Javascript method always get a dictionary we encapsulate it into {data:ret}.

Then in your Javascript, doing result.data will get you the value you are looking for.

Upvotes: 1

Related Questions