The Whiz of Oz
The Whiz of Oz

Reputation: 7043

How to load a div with Rails and ajax?

I have an index page full of products (products controller), and I can create orders by clicking on 'Order' button, which leads a user to the 'new' action of the order controller with the product id passed as a parameter.

  def new
    @order = Order.new
    @product = Product.find(params[:product])
  end

There the user can select the quantity he wants and finally create the order.

However I would like to make a modal window pop up instead when clicking 'order', with the form from the 'new order' page in it. So I've added the data-remote attribute to my Order button:

<%= link_to('Order', new_order_path(product: product), class: "btn btn-order", remote: true) %>

Updated thee controller:

def new
    @order = Order.new
    @product = Product.find(params[:product])

    respond_to do |format|
      format.html
      format.js
    end
  end

and created the new.js.erb file, that opens my modal window

function openModal = somecode...

But how do I grab the html of a FORM which lies beyond the link? I don't want to render partials, I just want the form code to be pasted into the .html('...') of my modal window!

Thanks!

Upvotes: 1

Views: 943

Answers (1)

dSquared
dSquared

Reputation: 9835

You can use jQuery to add the contents of the form to the DOM by rendering it as a partial in your new.js.erb file like so:

$('#modal_id').html('<%= escape_javascript(render(partial: "path/to/partial", object: @instance_variable)) %>');

EDIT: On a second read of your question, I see you mentioned that you do not wish to render partials, you could therefore simply have the form code directly in your new view; something like this:

var form_html = '<form>...</form>';
$('#modal_id').html(form_html);

I hope this helps!

Upvotes: 0

Related Questions