Brian Weinreich
Brian Weinreich

Reputation: 7702

Rails AJAX partial without submitting form

I'd like to create a page where there are two columns:

| Form to create a pizza | Suggested Pizzas |

As you use the form on the left column to create your pizza, the column on the right starts suggesting different types of pizza you could order based on the left customization.

All of the tutorials I have found bind the reloading of the partial to the form submission, however, I'd like for the partial to reload every time an input blurs or a select is changed.

Is there an easy way to do this with Rails?

I'd like to just grab the un-submitted @pizza object and send that to the partial every time a blur event occurs...

Upvotes: 0

Views: 266

Answers (2)

Arvind
Arvind

Reputation: 2781

controller

def my_pizza
  @pizza = Pizza.all
  respond_to do |format|
    format.js
  end
end

view

my_pizza.js.haml

$('#pizza').html('#{j render(partial: 'pizzas/piza', collection: @pizzs)}');

routes

get 'pizza' => "pizza#my_pizza"

Inside the js file

$(document).on('change', 'input', function() {
  // you can create your ajax call which will call the my_pizza method in which action you want to call. 
});

You can add ajax and what ever event you want to call you can call it easily and when you will call the respective method it will updated the partial file respectively

Upvotes: 1

Evil Buck
Evil Buck

Reputation: 1068

I think you gave yourself the answer. Just attach an event listener to the keyup's on the form and submit via ajax.

$('form').on('blur', function() {
  // submit ajax and do something with the response here
});

Upvotes: 0

Related Questions