Reputation: 96937
I have this controller:
class FormCreatorController
def build_form
if param[:ftype] == 2
@partial_file = "extra"
else
@partial_file = "basic"
end
respond_to do |format|
format.js
end
end
end
This is called from a new
view, where the code is like this:
<div class="column span-16 last">
<%= form_tag build_form_ads_path,:method => :get,:remote => true,:id => "ad_builder_form" do %>
<div class="column span-4">
<strong>Form type</strong>
</div>
<div class="column span-12 last">
<%= select_tag(:ad_type,options_for_select(@ad_types_mapped)) %>
</div>
<% end %>
<div class="column span-16 last" id="myform">
Please select an option
</div>
</div>
I am using jQuery as my ajax framework.
The myform
div, ideally
should be replace with the contents of what's returned from the build_form. I have this in the build_form.js.erb
:
$('#myform').html($('<%= render :partial => @partial_file %>'))
My basic form contains this:
<h1>Basic</h1>
My extra
form contains this:
<h2>Extra</h2>
But, when the XHR request is made, nothing happens to my div. If, however, I put this in my partials:
$('#myform').html("<h1>Basic</h1>")
and
$("#myform").html("<h1>Car</h1>");
then they are correctly displayed in the page. Building custom forms using javascript string concatenation is tedious, but doable. I am sure there is a better way of doing things. What should I do so that the code from my partials is correctly rendered instead of my div?
EDIT: maybe it helps. This is the content of my application.js:
$().ready(function() {
jQuery.ajaxSetup({
'beforeSend': function(xhr) {
xhr.setRequestHeader("Accept", "text/javascript");
}
});
$("#ad_type").change(function() {
$("#ad_builder_form").submit();
});
});
Every time the value of the select changes, I'm submitting the form with jQuery.
Upvotes: 0
Views: 157
Reputation: 10564
You can return the html update:
'<%= escape_javascript(render "#{param[:ftype].eql?(2) ? 'extra' : 'basic' }") %>'
then update the element client side.
$("#ad_type").change(function() {
$("#ad_builder_form").submit(function(){
$('myform').html(this);
});
});
or, to prevent problems with dynamically added html use jquery's live:
$('#ad_type').live('change', function() {
action = $('#ad_builder_form').attr('action');
$.post(action, jQuery.param(jQuery($('#ad_builder_form')).serializeArray()), function(data) {},
'script');
return false;
});
then return the script from your application as before:
$('#myform').html('<%= escape_javascript(render "#{param[:ftype].eql?(2) ? 'extra' : 'basic' }") %>'))
Upvotes: 1