Implementing ajax request to create/edit rails object - ruby-on-rails

I am trying to create a add/edit credit card form within my edit user page. To do so I am trying to implement an ajax call to the edit and create functions in my customers controller.
This is the code I have for the update button within the modal window:
<%= button_tag "Update", :class =>"btn submit-button", :type => 'button', :onclick => "onUpdateCard('#{current_user.id}');"%>
This is the function that it calls:
function onUpdateCard(id) {
this.id = id;
// disable the submit button to prevent repeated clicks
$('.submit-button').attr("disabled", "disabled");
var card_number = document.getElementById('card_number').value;
var card_code = document.getElementById('card_code').value;
var card_month = document.getElementById('card_month').value;
var card_year = document.getElementById('card_year').value;
var response = Stripe.createToken({
number: $('#card_number').val(),
cvc: $('#card_code').val(),
exp_month: $('#card_month').val(),
exp_year: $('#card_year').val()
}, stripeResponseHandler);
// allow the form to submit with the default action
return false;
};
function stripeResponseHandler(status, response) {
if (response.error) {
$(".payment-errors").text(response.error.message);
$(".submit-button").removeAttr("disabled");
} else {
var token = response['id'];
var new_url = "/users/" + this.id + "/customers/new";
var edit_url = "/users/" + this.id + "/customers/1/edit";
$.ajax({
type:'GET',
url: edit_url,
data: {'stripe_card_token': token}
});
}
return false;
};
And in the controller there is the edit function:
def edit
#user = current_user
#customer = #user.customer
stripe_customer = Stripe::Customer.retrieve(#customer.stripe_customer_token)
stripe_customer.card = params[:stripe_card_token]
stripe_customer.save
end
Can you help me figure out how to handle the ajax correctly? I'm not sure how to debug this properly...

Here I'm suggesting the alternative to handle update request using AJAX.
I'm not improving or correcting your code but giving you a way to handle AJAX requests in Rails 3.
a. view
Whatever information you wants to update in Database using AJAX call you will pass through a form. So for making a AJAX request you need to add :remote => true in your form. Rails provides this helper.
<%= form_for #customer, :url => admin_customers_path, :method => :post, :remote => true, :html => { :id => "customer-form" } do |form|-%>
<%= render :partial => 'admin/customers/form', :object => form %>
<%= form.submit 'Update' %>
<% end %>
In the _form.html.erb you can add textfield or other this whatever you wants to add in your edit form
b. controller
Because of " :remote => true " you form submission will make a JS request so in update action after saving the data of customer
control will for to format.js and then it will look for update.js.erb in views.
def update
if #customer.update_attributes(params[:customer])
respond_to do |format|
format.html {
flash[:success] = "customer's info was updated Successfully."
redirect_to customers_path
}
format.js
end
else
respond_to do |format|
format.html {
flash[:error] = #customer.errors.present? ? #customer.errors.full_messages.join('<br />') : "Oops! There is some problem with category update."
render :edit
}
format.js
end
end
end
c. update.js.erb
You can do stuffs after successful update. Suppose you want to highlight some div then you can do like this.
$('.target-div').effect("highlight", {}, 2500);

Related

Rails select2 after create new tag i haven't id on create action

I use select2 and want to create new tags and then save them.
i have form for #cost and for select2 this
<%= f.collection_select :product_ids, Product.all,:id, :name ,{include_hidden: false},{ multiple: true} %>
for creation new product i have this js code
$(document).ready(function () {
$('#cost_product_ids').select2({
tags: true,
tokenSeparators: [",", " "],
createProduct: function (product) {
return {
id: product.term,
text: product.term,
isNew: true
};
}
}).on("change", function (e) {
var isNew = $(this).find('[data-select2-tag="true"]');
if (isNew.length) {
$.ajax({
type: "POST",
url: "/product_new",
data: {product: isNew.val()}
});
}
});
});
and controller method for save new product
def product_new
product = Product.find_by(name:params[:product])
Product.create(name:params[:product]) if !product
render json: :ok
end
cost create action
def create
#cost = Cost.new(costs_params)
if #cost.save
flash[:notice] = t('added')
if params[:add_more].present?
redirect_back(fallback_location: root_path)
else
redirect_to #cost
end
else
render action: 'edit'
end
end
def costs_params
params.require(:cost).permit(:day, :amount, :description, :source,:tag_list,:product_ids=>[])
end
it works ok, but when i want to save my #cost record with this newly created product i have received only name of my tag without id.
For example i have products water=>id:1,beer=>id:2,and create new juice tag in db it has id:3
on create in have params "product_ids"=>["1", "2", "juice"]
How to fix it?
you shouldn't use id: product.term,
but id: product.id,

Checkbox in index view live updating

I'm currently learning rails and working on what I'm sure is everyone's first rails app, a simple todo list. I need to implement a checkbox next to the items to indicate whether they are complete or not. Each item has a boolean attribute called "completed" in their model. I have found a couple checkbox questions while searching but none explain the syntax very easily in the context of the index view.
Also, I really want the checkbox to work without a submit button. I know I could accomplish something like this using AngularJS's ng-model but I don't think it would be practical to implement angular for such a small thing and I don't know how angular works with rails.
If anyone could give me a pointer in the right direction, it would be greatly appreciated. Here's my index.html.erb for reference.
<h1>
To Do List
</h1>
<table>
<tr>
<% #todo_items.each do |item| %>
<!-- Checkbox here -->
<tc style="<%= 'text-decoration: line-through' if item.completed %>">
<%= link_to item.title, item %>
</tc>
<tc>
<%= item.description %>
</tc>
<tc>
<%= link_to "Edit", edit_todo_item_path(item) %>
</tc>
<tc>
<%= link_to "Delete",item, data:{:confirm => "Are you sure you want to delete this item?"}, :method => :delete %>
</tc>
<hr/>
<% end %>
</tr>
</table>
<p>
<%= link_to "Add Item", new_todo_item_path %>
</p>
This is my way, I don't know this way is right direction or not but this works for me (also different case but same of concept).
views for checkbox
You could put an id item or something into attribute of checkbox for find an object in controller if you send data to controller for get record of object, and you could define if attribute completed of record is true or false:
<%= check_box_tag :completed_item, 1, item.completed? ? true : false, { class: 'name-of-class', data: { id: item.id} } %>
controller
You need two action call set_completed and remove_completed, and also you don't need templates for them, just use format as json:
before_action :set_item, only [:set_completed, :remove_completed, :other_action]
def set_completed
#item.set_completed!
respond_to do |format|
format.json { render :json => { :success => true } }
end
end
def remove_completed
#item.remove_completed!
respond_to do |format|
format.json { render :json => { :success => true } }
end
end
private
def set_item
#item = Item.find params[:id]
end
Model
For set_completed! and remove_completed! you could define in your model
def set_default!
self.update_attributes(:completed => true)
end
def remove_default!
self.update_attributes(:completed => false)
end
routes
resources :address do
collection do
post 'set_completed'
post 'remove_completed'
end
end
Also, you need help JavaScript for handle send request from view to controller event click of checkbox:
jQuery
$(".completed_item").click(function(){
var check = $(this).is(":checked");
if (check == true){
set_completed($(this).attr('data-id'));
} else{
remove_completed($(this).attr('data-id'));
}
});
function set_completed(data_id) {
$.ajax({
type: 'POST',
url: "/items/set_completed",
data: { id: data_id},
dataType: 'json',
success: function(response){
if(response){
}else{
alert('error');
}
}
})
}
function remove_compelted(data_id) {
$.ajax({
type: 'POST',
url: "/items/set_completed",
data: { id: data_id},
dataType: 'json',
success: function(response){
if(response){
}else{
alert('error');
}
}
})
}

Ajax:success not working in rails app

Within a rails 4 app, I am using a link_to to send an upvote on posts via json.
Here is what I have in my posts controller:
def upvote
#post = Post.find(params[:id])
#post.liked_by current_user
respond_to do |format|
format.html {redirect_to :back }
format.json { render json: { count: #post.get_upvotes.size } }
end
end
Here is what I have in my view
<%= link_to like_post_path(post), method: :put, class: 'vote', remote: true, data: { type: :json } do %>
<%= image_tag('vote.png') %>
<%= content_tag :span, post.get_upvotes.size %>
<% end %>
<script>
$(document)
.on('ajax:send', '.vote', function () { $(this).addClass('loading'); })
.on('ajax:complete', '.vote', function () { $(this).removeClass('loading'); })
.on('ajax:error', '.vote', function(e, xhr, status, error) { console.log(status); console.log(error); })
.on('ajax:success', '.vote', function (e, data, status, xhr) {
$(this).find("span").html(data.count);
$(this).find("img").attr("src", '<%= asset_path 'voted.png' %>');
});
</script>
When I click on the link, the vote goes through as a JSON request, I see this in my log:
Processing by PostsController#upvote as JSON
But for some reason, my snipped of javascript is not working. Neither the counter or the icon update. How can I fix this? Does this have to do with turbolinks, does it have to do with where I am placing the javascript?
In Rails you can perform a similar task by having a JavaScript response. Add in your respond_to a format.js similar to format.html then have a view upvote.js.erb that looks like:
(function() {
var postId = "#post-<%= #post.id %>";
$(postId).find(".vote").find("span").text("<%= #post.get_upvotes.size %>");
$(postId).find(".vote").find("img").attr("src", "<%= asset_path "voted.png" %>");
})();
I changed your call to .html to .text since you're not actually setting any HTML inside the element, there is no reason to call .html.
This post also assumes there is some mechanism to identify the post the vote link belongs to (in the example the parent post element has an ID of "post-#" where # is the ID of the post object).
EDIT
Two changes I'd make if I were working on this project. First I would attach the voted.png path to the .vote element as a data attribute. data-voted-image-src="<%= asset_path "voted.png" %>". Next, I would never pass a number in the return as there is no reason to do so. When the vote is clicked you can handle everything on the front end by assuming the request is successful. Which saves all this potential nastiness. While I realize that changing from what you current have to adding the data attribute isn't a huge leap I just find it more semantic than having it in the JavaScript.
The click action on the vote link then becomes:
// Assume all posts have a class 'post'
// I'm also using 'one' because once they vote they don't need to anymore
$(".post").find(".vote").one("click", function(e) {
var count = parseInt($(this).find("span").text()),
votedSrc = $(this).data("voted-image-src");
$(this).find("img").attr("src", votedSrc);
$(this).find("span").text(count + 1);
});
Now no response from the server is necessary, and you can change your JSON response to {success: true} or something simple.
jQuery is the default rails javascript library. The default rails javascript library used to be prototype, so old tutorials/docs use it. This is what the ajax looks like with jQuery:
app/controllers/static_pages_controller.rb:
class StaticPagesController < ApplicationController
def show_link
end
def upvote
respond_to do |format|
format.json {render json: {"count" => "10"} }
end
end
end
app/views/static_pages/show_link.html:
<div>Here is an ajax link:</div>
<%= link_to(
"Click me",
'/static_pages/upvote',
'remote' => true, #Submit request with ajax, and put text/javascript on front of Accept header
data: { type: :json }) #Put application/json on front of Accept header
%>
<div>Upvotes:</div>
<div id="upvotes">3</div>
<script>
$(document).ready( function() {
$(this).ajaxSuccess( function(event, jqXHR, ajaxInfo, data) {
//var js_obj = JSON.parse(jqXHR.responseText);
//$('#upvotes').html(js_obj["count"]);
//Apparently, the fourth argument to the handler, data,
//already contains the js_obj created from parsing the
//json string contained in the response.
$('#upvotes').html(data["count"]);
});
});
</script>
config/routes.rb:
Test1::Application.routes.draw do
get 'static_pages/show_link'
get 'static_pages/upvote'
...
end
url to enter in browser:
http://localhost:3000/static_pages/show_link
See jquery docs here:
http://api.jquery.com/ajaxSuccess/
Response to comment:
You could also do the following in your controller:
def upvote
#upvotes = 2 #Set an #variable to the number of upvotes
respond_to do |format|
format.js {} #By default renders app/views/static_pages/upvote.js.erb
end
end
Then:
app/views/static_pages/upvote.js.erb:
$('#upvotes').html(<%= #upvotes %>)

Ruby on Rails - drop down box on change event

I have two drop down boxes in my application.
Based on the value selected in 1st combobox, the values in 2nd drop down box should be populated.And these values should come from Database.
Please help me.
here's a clean approach using jquery-ujs (https://github.com/rails/jquery-ujs)
In your view:
<%=
select_tag
:first_select, # name of selectbox
options_from_collection_for_select(#myrecords, "id", "name"), # your options for this select box
:'data-remote' => 'true', # important for UJS
:'data-url' => url_for(:controller => 'MyController', :action => 'getdata'), # we get the data from here!
:'data-type' => 'json' # tell jQuery to parse the response as JSON!
%>
<%=
select_tag
:second_select, # name of selectbox
"<option>Please select something from first select!</option>"
%>
Your Controller:
class MyController < ApplicationController
def getdata
# this contains what has been selected in the first select box
#data_from_select1 = params[:first_select]
# we get the data for selectbox 2
#data_for_select2 = MyModel.where(:some_id => #data_from_select1).all
# render an array in JSON containing arrays like:
# [[:id1, :name1], [:id2, :name2]]
render :json => #data_for_select2.map{|c| [c.id, c.name]}
end
end
In your application.js:
$(document).ready(function() {
// #first_select is the id of our first select box, if the ajax request has been successful,
// an ajax:success event is triggered.
$('#first_select').live('ajax:success', function(evt, data, status, xhr) {
// get second selectbox by its id
var selectbox2 = $('#second_select');
// empty it
selectbox2.empty();
// we got a JSON array in data, iterate through it
$.each(data, function(index, value) {
// append an option
var opt = $('<option/>');
// value is an array: [:id, :name]
opt.attr('value', value[0]);
// set text
opt.text(value[1]);
// append to select
opt.appendTo(selectbox2);
});
});
});
You could take inspiration from what I have in a project of mine. It updates the state given the country selected.
It makes use of Carmen a great gem listing countries, states etc...
View:
<p>
<label>Country <span>*</span></label>
<%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %>
</p>
<p>
<label>State <span>*</span></label>
<%= profile_form.select(:state, "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %>
</p>
Jquery code:
$('#profile_country').change(function() {
if ($(this).val() == '')
{
$('#profile_state').html( $('<option>No state provided for your country</option>'));
}
else {
$.ajax({
type: "GET",
url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')),
success: function(data){
if (data.content == 'None') //handle the case where no state related to country selected
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>No state provided for your country</option>'));
}
else
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>Select your State</option>'));
jQuery.each(data,function(i, v) {
$('#profile_state').append( $('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>'));
});
}
}
});
}
});
Controller:
def states
begin
render :json => Carmen::states(CGI::unescape(params[:country]))
rescue
render :json => {"content" => "None"}.to_json
end
end
This is how I did it. Works in Rails 3.2
View:
<%= select_tag :major_category_select_id, options_from_collection_for_select(#majorcategories, 'id', 'name'), :'data-remote' => 'true', :'data-url' => url_for(:controller => 'listings', :action => 'submit_major_category', format: 'js') %>
Controller method:
def submit_major_category
#major_category = MajorCategory.find(params[:major_category_select_id])
#minor_categories = #major_category.minor_categories
respond_to do |format|
# format.html { render partial: 'minor_categories_select' }
format.js
end
end
Routes:
get "listings/submit_major_category"
Then create a submit_major_category.js.erb file that gets responded to.

Rails checkbox AJAX call, don't want to render anything

I've got a little demo setup in which clicking a checkbox toggles an attribute via AJAX. It's working fine, but Rails REALLY wants to render something, so I've basically resorted to creating a blank toggle.js.erb file in my views.
Controller action in question:
def toggle
#task = Task.find(params[:id])
respond_to do |format|
format.js do
if (#task.status != true)
#task.status = true
else
#task.status = false
end
#task.save
render :layout => false
end
end
end
View in question:
<h1>Tasks</h1>
<ul style="list-style-type: none;">
<% #tasks.each do |task| %>
<li id="<%= dom_id(task) %>">
<%= check_box_tag(dom_id(task), value = nil, checked = task.status) %>
<%= task.action %> <%= link_to 'Edit', edit_task_path(task) %>
<%= link_to 'Delete', task, :confirm => 'Are you sure?', :method => :delete, :remote => true %>
</li>
<% end %>
</ul>
<%= link_to 'New Task', new_task_path %>
<script>
$$('input').each(function(el) {
el.observe('click', function(event) {
// Get the task ID
var elId = el.id.split("_")[1];
// Build the toggle action path
var togglePath = '/tasks/' + elId + '/toggle/';
// Create request, disable checkbox, send request,
// enable checkbox on completion
new Ajax.Request(togglePath, {
onCreate: function() {
el.disable();
},
onSuccess: function(response) {
},
onComplete: function() {
el.enable();
}
});
});
});
</script>
Without the blank toggle.js.erb file I've got in the views, Rails still gives me an error saying that it's trying to render something.
Ultimately, I'd like to both not have to have a blank toggle.js.erb file, and I'd like to get that Prototype stuff into my static JavaScript stuff and out of the view.
I'm pretty new to Rails, so there's probably an easier way to be doing this, but I'm kind of stuck here.
render :layout => false means that you want to render 'toggle' view without layout.
If you don't want render anything at all, you should use :nothing => true option
def toggle
#task = Task.find(params[:id])
#task.toggle! :status
# if it used only by AJAX call, you don't rly need for 'respond_to'
render :nothing => true
end
EDIT: In Rails4/5 you can use head :ok instead of render nothing: true, it's more preferable way to do this, but result is the same.

Resources