user3437721
user3437721

Reputation: 2299

Rails - having a ajax button to make call

Say I have a button on my form, it doesn't submit the form, but it basically goes off to get some more information:

<%= f.button '', class:'hidden', id: 'do_calculation', remote: true %>

How do I tie this up so that when it is clicked it calls a controller action and returns the data?

Should I have something like this on the same page?

<script>
  function calculate_close() {
    var id = '<%= @thing.id %>';
    $.ajax({
      url: "<%= calculate_path %>",
      data: {
        id: id
      },
      dataType: "script"
    })
  }

</script>

Upvotes: 0

Views: 1116

Answers (1)

power
power

Reputation: 1265

Here you can create a html button without using form builder like.

<button id="do_calculation">Button</button>

Then you can bind the click event to that button and call the ajax inside that event, like:

$("#do_calculation").on('click', function(){
  var id = '<%= @thing.id %>';
  $.ajax({
    url: "<%= calculate_path %>",
    data: {
      id: id
    },
    dataType: "json"
  })
})

and in the controller you can use something like:

respond_to do |format|
  format.json { render :json => {:message => "success"} }
end

Hope this will help!

Upvotes: 1

Related Questions