Rails - having a ajax button to make call - ruby-on-rails

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>

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!

Related

Passing in rails routes to AJAX url value

I have an app where a user has a portfolio that has many positions and each position has many movements. So the url for an associated movement index page for a particular position looks like: portfolio_position_movements. I have an index page with and the controller action looks like
def index
#movements = #position.movements.all
respond_to do |format|
format.html
format.json { render json: #movements}
end
end
My ajax call in my movements.js file is this:
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: ?,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
How can I pass in a dynamic route path so this will work with the movement index on any position object?
You can use erb tags in js files, for me i did it as the following:
#edit.js.erb
$modal = $('.modal'),
$modalBody = $('.modal .modal-body'),
$modalHeading = $('.modal .modal-heading');
$modalHeading.html("Edit <%= #student.full_name.titleize %>'s information");
$modalBody.html("<%= escape_javascript(render 'edit_student') %>");
$modal.modal();
Note: the file extension is .js.erb so rails can process it. I was calling a modal form and the edit method in students_controller.rb was:
def edit
#student = Student.find(params[:id])
respond_to do |format|
format.html # edit.html.erb
format.js # edit.js.erb
format.json { render json: #student }
end
end
Edit:
You can embed the JS code inside html.erb and use rails routes like:
<script>
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: <%= my_ajax_path %>,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
</script>
What is my_ajax_path?
Is a rails route defined in routes.rb for example i need a list of all available sections that students can apply to using ajax so i did the following:
1- defined a method in students_controllers.rb like this one:
def available_sections
batch_id = (params[:batch_id].nil? || params[:batch_id].empty?) ? 0 : params[:batch_id].to_i
if batch_id == 0
#sections = [].insert(0, "Select Section")
else
batch = Batch.find(params[:batch_id])
# map to name and id for use in our options_for_select
#sections = batch.sections.map{|a| [a.section_name, a.id]}
end
end
2- added a route to it in routes.rb
resources :students do
collection do
get :available_sections
post :create_multiple
end
end
3- Inside new.html.erb:
<script type="text/javascript">
$(document).ready(function() {
$('.student_section_id').hide();
$('#student_batch').change(function() {
$.ajax({
url: "/students/available_sections",
data: {
batch_id : $('#student_batch').val()
},
dataType: "script",
success: function () {
if (+$('#student_batch').val() > 0)
{
$('.student_section_id').fadeIn();
}
else
{
$('.student_section_id').fadeOut();
}
}
});
});
});
</script>
Forget about that messy code :D as it was my first steps but you get the point, and for this line url: "/students/available_sections" it should be using rails routes you can get it by calling rails routes from the command line to get a list of all your application routes

send data from view to controller in rails

I want to send some data from view to controller in rails through ajax.
I have the following code in
app/view/static/home.html.erb
<script type="text/javascript">
var dummy = "testtext";
$('#finish').click(function() {
$.ajax( {
url: '/finish',
type: 'POST',
data: dummy,
dataType: 'text'
});
});
</script>
<body>
<%= button_to "Finish", {:action => 'finish', :controller => 'static'}, :method => :post, id => 'finish' %>
</body>
in
app/view/static/finish.html.erb
<p><%= #data %></p>
app/controller/static_controller.rb
def finish
#data = params[:data]
end
in routes.rb
post 'finish' => 'static#finish'
My understanding is that on button click the ajax script will be executed and rails action will store the data passed from view. This doesn't seem to work. I'm not sure if my understanding of the flow is right.
Because you are calling params[:data] in the controller, you need to specify that {data: dummy} in the AJAX data section
<script type="text/javascript">
var dummy = "testtext";
$('#finish').click(function() {
$.ajax( {
url: '/finish',
type: 'POST',
data: {data: dummy},
dataType: 'text'
});
});
</script>
Also you might want to respond to your AJAX call in your controller using the following
def finish
#data = params[:data]
respond_to do |format|
format.json { insert_your_code_here }
end
end

Rails + React js + react-rails gem submit form with single component

I am trying to submit form in react js with Rails.
I am new to React js and it is my first app
I am getting error No route matches [POST] "/"
Using single component(jsx) to submit the form.I am getting routing error.
Following is my code
EDIT
I changed the route and now I got error "InvalidAuthenticityToken in ItemsController#create"
How can i raise or alert variable in in jsx file ?
I add following route in route.rb
resources :items
root :to => redirect("/items")
ItemsController
def index
#presenter = { :action => items_path,
:csrf_token => request_forgery_protection_token,
:csrf_param => form_authenticity_token
}
end
def create
#item = Item.new(item_params)
#item.save
end
private
def item_params
params.require(:item).permit(:name, :price)
end
Index.html.erb
<%= react_component('Form1', {:presenter => #presenter.to_json}, {:presenter => true})%>
Form1.js.jsx
var Form1 = React.createClass({
handeSubmit: function( e ){
e.preventDefault();
// var form = e.target;
// var name = form.querySelector('[name="item[name]"]').value;
// var price = form.queySelector('[name="item[price]"]').value;
var name = this.refs.name.getDOMNode().value.trim();
var price = this.refs.price.getDOMNode().value.trim();
if(!name || !price)
{
return false;
}
var formData = $( this.refs.form.getDOMNode() ).serialize();
var action = this.props.presenter.action
// alert({formData});
$.ajax({
data: formData,
url: action,
type: "POST",
dataType: "json",
});
},
render: function(){
return (
<form ref="form" className="" action={ this.props.presenter.action } acceptCharset="UTF-8" method="post" onSubmit={this.handleSubmit} >
<input type="hidden" name={ this.props.presenter.csrf_param } value={ this.props.presenter.csrf_token } />
<input ref="name" name="item[name]" /><br/>
<input ref="price" name="item[price]" /><br/>
<button type="submit"> Submit</button>
</form>
)
}
});
It looks like, for AJAX requests, you should send the CSRF token as a header, not as a form field.
(Docs: http://api.rubyonrails.org/classes/ActionView/Helpers/CsrfHelper.html#method-i-csrf_meta_tags)
Here's how you could add that header in your case:
var csrfToken = this.props.presenter.csrf_token;
$.ajax({
data: formData,
url: action,
type: "POST",
dataType: "json",
// Before sending, add the CSRF header:
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
});
Does that work for you?
By the way, one way I work around this is by using react_component for form fields, but using Rails' form_for to make the actual <form> tag. For example,
<%= form_for #item, remote: true do |f| %>
<!-- Rails will add CSRF token -->
<%= react_component("ItemFormFields", item: #item) %>
<% end %>

Rails AJAX (JSON) response reloads the page

In the controller a response to an AJAX Request is following:
#response = {resp: "ack"}
render json: #response
JS which handles AJAX is:
$('#some_btn').click(function() {
var valuesToSubmit = $('#some_form').serialize();
var url = $('#some_form').attr('action');
console.log("VALUE: " + valuesToSubmit);
console.log("URL: " + search_url);
$.ajax({
type: 'POST',
url: url, //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON",
success: function(data) {
console.log("saved");
console.log(data);
}
});
return false;
});
But the problem is that I don't get console messages, instead the page reloads and I get json as text on a new page. How to prevent this "non-true-AJAX" behaviour?
So, I had almost the same problem. In my case, I was using the folliwing link to send the request:
<td>
<%= link_to add_item_path(item),
class: 'ui icon button',
id: "add-item-#{item.id}",
method: :post do %>
<%= fa_icon 'shopping-cart' %>
<% end %>
</td>
My js to send the ajax was:
$(document).ready(function() {
$("a:regex(id,add-item-[0-9]+)").click(function(event) {
event.preventDefault();
var link = $(this).attr("href");
$.ajax({
url: link,
method: "POST",
dataType: "json",
success: function(data) {
console.log(data);
$('#notice-modal').modal('show');
}
});
})
});
and my rails controller action was:
def add
#item = Item.find(params[:item_id])
current_cart << { item_id: #item.id, quantity: 1 }
render json: {quantity: 1}
end
So the problem was I using only event.preventDefault() but wasn't enought. For working fine, I need to use event.stopPropagation(). Like this:
$("a:regex(id,add-item-[0-9]+)").click(function(event) {
event.preventDefault();
event.stopPropagation();
var link = $(this).attr("href");
$.ajax({
url: link,
method: "GET",
dataType: "json",
success: function(data) {
console.log(data);
$('#notice-modal').modal('show');
}
});
})
The event.stopPropagation() is needed because rails component (rails-ujs I think) sent the request elsewhere. You can also remove the method: :post, and will work fine.
Hope I helped!
Do you need to prevent the default form submit action?
$('#some_btn').click(function(event) {
event.preventDefault();
//...
});
I had this problem myself. Turns out, I'd just forgotten to add "//= require jquery_ujs" to my application.js file. As soon as I added it, everything worked fine.

Getting 2 variables from 1 ajax call in ruby on rails

I was wondering how you can get 2 variables to update a div tag using an ajax call instead of just 1. My current .js file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data);
}
});
});
});
show.html.erb where i get the data:
<%= #product.item %>
I would like something like this
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data[1]);
$("#price").empty().append(data[2]);
}
});
with
<%= #product.item %>
<%= #product.price %>
where my description div gets updated with #product.item and my price div gets updated with #product.price. How could I achieve this?
EDIT
updated .js file
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "json",
success: function(data) {
$("#description").empty().append(product.item);
$("#price").empty().append(product.price)
}
});
});
});
show.html.erb:
<%= #product.item %>
<%= #product.price %>
controller:
class ProductsController < ApplicationController
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product.to_json }
end
def index
end
def show
#product = Product.find(params[:id])
end
end
I'm pretty sure that controller isn't correct. I placed #product before respond_to and it didn't work so I just put respond_to without really knowing where it goes. Sorry for being such a noob. Thanks for all your help.
FINAL EDIT:
working javascript file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.getJSON("/products/"+selected_product_id,function(data){
$("#description").empty().append(data.item);
$("#price").empty().append(data.price);
});
});
});
Ah, This remembers me a piece of code I wrote for you a week ago!
You can use JSON to render your Product:
#controller
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product.to_json }
end
end
And handle the response from the server like this:
$.ajax({
url: "/products/" + selected_product_id,
dataType: 'JSON',
success: function(data) {
var product = JSON.parse(data);
$("#description").empty().append(product.item);
$("#price").empty().append(product.price);
}
});
Edit #1: I found this method: jQuery.getJSON : http://api.jquery.com/jQuery.getJSON/
You could use JSON, return
{"item": "<%=j #product.item %>", "price": <%= #produce.price %>}
then type: 'json' in the ajax call

Resources