Sorry if this is a stupid question, but I can’t get this to work. I am trying to get a form within a dialog panel. The form is the result of an AJAX request and the resulting js.erb file looks like:
$(function() {
$('#add_tag').html(
"<fieldset>"
"<%= escape_javascript(form_tag(save_tag_path(:id=>@recipe.id), :remote=>true) do ) %>" +
" <%= escape_javascript(label_tag(:new_tags, 'Your tags separated by commas')) %>" +
" <%= escape_javascript(text_field_tag :new_tags) %>" +
" <%= escape_javascript(submit_tag :submit) %>" +
"<% end %>" +
"</fieldset>"
);
$('#add_tag').dialog({
title: "Add Tags",
height: 300,
width: 350,
modal: true
}
);
});
I know the form syntax is ok because it works outside the dialog. I’m assuming it’s something not being escaped properly? Thanks in advance!
UPDATE: I removed the $(function(){} wrapper as Ben Simpson correctly pointed out. However, I still get nothing rendered in my panel using erb. Here is what I have now:
$('#add_tag').html(
"<fieldset>"
+ "<%= form_tag(save_tag_path(:id=>@recipe.id), :remote=>true) do %>"
+ " <%= escape_javascript(label_tag(:new_tags, 'Your tags separated by commas')) %>"
+ " <%= text_field_tag :new_tags %>"
+ " <%= submit_tag :submit %>"
+ "<% end %>"
+ "</fieldset>"
);
$('#add_tag').dialog({
title: "Add Tags",
height: 300,
width: 350,
modal: true
}
);
But if I just put in the form that rails renders it works. Ie:
$('#add_tag').html(
"<fieldset>"
+ '<form method="post" data-remote="true" action="/recipes/1/save_tag" accept-charset="UTF-8">'
+ '<div style="margin: 0pt; padding: 0pt; display: inline;">'
+ '</div>'
+ '<label for="new_tags">Your tags separated by commas</label>'
+ '<input id="new_tags" type="text" name="new_tags">'
+ '<input type="submit" value="submit" name="commit">'
+ '</form>'
+ "</fieldset>");
Your response is wrapped within a “$(function() {}” closure, which is jQuery shorthand for binding to the DOM:loaded event. This has already been fired as the page has been loaded.
Remove this line, and your function should automatically evaluate.
Javascript inside an AJAX response should be evaluated automatically as long as the MIME type is text/javascript. More information on jQuery AJAX responses can be found here: http://api.jquery.com/jQuery.ajax/