user3437721 user3437721 - 4 months ago 14
Ajax Question

Rails - having a ajax button to make call

Say I have a button on my form, it doesnt 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 this this on the same page?

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

</script>

Answer

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!