I’m building a form that allows users to enter a word, and when they tab off I query a dictionary(Wordnik.com) to retrieve the definitions, and add the definitions as radio button selections to the form. The javascript picks up the word, calls the get_definition function in my WordsController and queries the dictionary API, but I can’t seem to get the partial to render (right now it just prints out “<%= escape_javascript…..%>”)
PS: I also tried querying the api directly with jquery (so I’m not hitting the get_definitions function) but I couldn’t get the request to send, so I’m sticking with the above method for now.
words_controller:
def index
@words = Word.where(user_id: current_user)
@word = current_user.words.new
@defs = Array.new
end
def get_definition
@defs = Wordnik.word.get_definitions(params['word'])
render nothing: true
end
javascript:
$('input#word_name').blur(function(){
var word = $('input#word_name').val();
$.ajax({
url: '/words/get_definition',
data: 'word='+word
})
$('#addDefinitionContainer').html("<%= escape_javascript(render partial: 'words/definitions', locals: {f: f}) %>")
})
_definitions partial:
<% @defs.each do |definition| %>
<div class="definition_choice">
<%= f.label definition %>
<%= f.radio_button :definition, "yes" %>
</div>
<% end %>
Instead of trying to render the ruby partial in javascript I decided to manually add the form elements instead, in js. After the ajax call to my ruby method, I call the following method as the callback:
This adds a radio button (with associated text) to the page for each definition I receive. However, the radio button chosen by the user doesn’t get send along with the word in the POST request. The solution of which is to call the jquery serialize() function on the form upon submission:
I suppose since these added form elements (radio buttons) aren’t in the DOM when the page first renders, they won’t be looked for upon form submission. The serialize function goes over the form as it is now and prepares a new string to be sent.