JQuery doesn`t fire/work with my Rails 3.2 project - javascript

As in the title, I`ve made sure all needed JS files are included in the meta tags, included the jquery-rails/coffee-rails gem, linked to a external one just in case.
This is a modified script from Ryan Bates tutorial on Stripe, from what I understand it`s suppose to fire up by detecting the submit action from the form.
Since I'm not that familiar with JS or CoffeeScript, I can't really pin point what's the problem here.
Would appreciate any help I can get.
The donations.js file:
jQuery ->
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
donation.setupForm()
donation =
setupForm: ->
$('#new_donation').submit ->
$('input[type=submit]').attr('disabled', true)
if $('#card_number').length
donation.processCard()
false
else
true
processCard: ->
card =
number: $('#card_number').val()
cvc: $('#card_code').val()
expMonth: $('#card_month').val()
expYear: $('#card_year').val()
Stripe.createToken(card, donation.handleStripeResponse)
handleStripeResponse: (status, response) ->
if status == 200
alert(response.id)
else
alert(response.error.message)
The donations/new.html.erb form
<%= form_for(#donation) do |f| %>
<div class="field">
<%= f.label :from %>
<%= f.text_field :from %>
</div>
<div class="field">
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, :name => nil %>
</div>
<div class="field">
<%= label_tag :card_code, "Security Code (CVV)" %>
<%= text_field_tag :card_code, nil, :name => nil %>
</div>
<div class="field">
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {:add_month_numbers => true}, {:name => nil, :id => "card_month"} %>
<%= select_year nil, {:start_year => Date.today.year, :end_year => Date.today.year+15}, {:name => nil, :id => "card_year"} %>
</div>
<div class="field">
<%= f.label :Notes %>
<%= f.text_field :note %>
</div>
<br>
<center>
<span class="BigBold">Amount: $2.50</span>
<%= f.hidden_field :amount, {:value => "2,5" } %><br>
</center>
<br>
<center>
<%= f.submit "Donate Now", :class => 'donate-button' %>
</center>
<% end %>

Your javascript seems to be, well, Coffeescript - make sure it's put in its own donations.js.coffee file, and that you're including the coffee-rails gem while you're at it.
Standard debugging techniques would be useful here - try adding an alert("It lives!") or something after the initial jQuery -> line to see if the document.ready handler is ever being called.
If not, check to make sure that the donations.js.coffee file is being loaded in the first place, and if not, make sure you're either loading it in your page's header, or you have something like this in application.js:
//= require jquery
//= require donations
Or, if you just want to include everything in app/assets/javascripts:
//= require jquery
//= require_tree .

Peter is correct, your coffeescript code should be properly named so that it can be translated to JavaScript.
An additional debugging strategy is to look at the html/js source being sent to your browser. Use the view source command to see the html source. Then click on the reference to the js link containing the translated donations.js.

Related

Error: ActionController::Unknown Format (for format.js)

I'm completing a project. I have a search field that accepts a url. Upon submit, my code scrapes data from a website and saves it in a variable. I want to use that data to automatically fill in form fields for the user on that same page.
Here's what I currently have in the view:
<%= provide(:title, "New Deal") %>
<h3 class="create">Step 1: <span class="text">Enter the wholesale URL and click add button to create a new deal.</span></h3>
<%= form_tag new_deal_path, id: "search-form", method: :get do %>
<p>
<%= label_tag(:search, "Enter the URL:") %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Add Deal", name: nil, class: "scrape-trigger", remote: true %>
</p>
<% end %>
<% end %>
Here's my controller action:
def new
if params[:search]
#response = Deal.search(params[:search])
respond_to do |format|
format.js
end #currently, can't get this to work.
end
#deal = Deal.new
#deal.orders.build
#user = User.new
end
And here is the form I want to fill:
<div class="manual-deal">
<%= f.label :url %><br>
<%= f.url_field :url %><br><br>
<%= f.label :title %><br>
<%= f.text_field :title %><br><br>
<%= f.label :image %><br>
<%= f.file_field :image %><br><br>
<%= f.label :retail_price_cents %><br>
<%= f.text_field :retail_price_cents %><br><br>
<%= f.label :wholesale_price_cents %><br>
<%= f.text_field :wholesale_price_cents %><br><br>
<%= f.label :minimum_bids %><br>
<%= f.number_field :minimum_bids %><br><br>
<%= f.label :estimated_delivery %><br>
<%= f.date_field :estimated_delivery %><br><br>
<%= f.label :delivery_method %><br>
<%= f.select :delivery_method, ['USPS', 'UPS', 'FedEX', 'Shyp', 'Local Pickup'] %><br><br>
<%= f.label :description %><br>
<%= f.text_area :description %><br>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="Charge"
data-amount="<%=#deal.wholesale_price_cents%>">
</script>
<% end %>
Following the advice on another question, I created a new.js.erb file in the view where I want this to happen. I thought I could fill the fields from there using:
function ready() {
$('.scrape-trigger').on("click", function() {
$('#deal_url').val(params[:search]);
$('#deal_title').val(title);
$('#deal_image').val(image);
$('#deal_wholesale_price_cents').val(price_range);
$('#deal_description').val(description);
});
};
$(document).on('ready page:load', ready)
Not quite sure about this last part. Can someone point me in the right direction? I've been stuck on this for hours and haven't found a decent solution. I've found some other resources on Ajax, but nothing that works with what I need with this scraped data.
Cheers.
I'm assuming #response has all the information you're going to need when filling out the form. (Also note that #deal and #user will not be available to new.js.erb because they are defined after you render that file.)
This .js.erb file is rendered exactly once, exactly when it is rendered. Because of that, you don't need to worry about any $(document).on('ready page:load', ready) nonsense. You don't want this code to run when the page has loaded, you want it to run when the file is rendered. Get rid of it!
You should be left with just the .val() lines. This is a fine way to go about setting the value of things, but this file has no idea what params[:search] or title is. The only variable you passed to this file is #response. Use it!
So you should end up with something like the following:
$('#deal_url').val(#reponse.url);
$('#deal_title').val(#reponse.title);
$('#deal_image').val(#reponse.image);
$('#deal_wholesale_price_cents').val(#reponse.price_range);
$('#deal_description').val(#reponse.description);

Rails - fields_for and javascript to dynamically add and remove fields in a form (railscasts ep. 196-197)

UPDATE
Thank you for your answer.
But If I remove
for requested_role in #project.requested_roles
from the partial, then I can't access to the requested_role.role value, because I don't have the parameter X obtained from the code
for X in #projects.requested_roles
and I can't write X.role
How can I access this value without using for or .each to scroll the requested_roles of the project?
END UPDATE
I've a problem with a social network I'm developing with Ruby on Rails. I followed the railscasts 196 and 197 to create a form with fields_for and to add fields dinamically with javascript, but I have 2 major problems.
A User can create a Project and this Project must have 1+ Requested_roles.
When I open the project edit page to change the roles, if there are N requested_roles for the project, I see N*N forms to change the requested_roles. So if I have 2 requested_roles (for example Director and Producer) I see 4 select fields, Director - Producer - Director -Producer. They are repeated N times. And I can't modify them because I can have max 1 requested_role of each type. It's fine if I have only 1 requested_role (because 1x1=1)
Project.rb
class Project < ActiveRecord::Base
attr_accessible :title, :requested_roles_attributes, :video, :num_followers, :num_likes
belongs_to :user
has_many :requested_roles, dependent: :destroy
accepts_nested_attributes_for :requested_roles, :reject_if => lambda { |a| a[:ruolo].blank? }, :allow_destroy => true
Requested_role.rb
class RequestedRole < ActiveRecord::Base
attr_accessible :role, :project_id
belongs_to :project
Projects_controller.rb
class ProjectsController < ApplicationController
def new
#project= Project.new
#requested_role= #project.requested_roles.build
end
Projects/edit.html.erb
<div class="row">
<div class="span6 offset3">
<%= form_for(#project) do |f| %>
<%= render 'shared/error_messages', object: f.object%>
<%= f.label :title, "Project title" %>
<%= f.text_field :title %>
<%= f.fields_for :requested_roles do |builder| %>
ciao
<%= render 'requested_role', :f => builder %>
<% end %>
<div class="fields">
<p><%= link_to_add_fields "Add requested role", f, :requested_roles %></p>
</div>
</br>
<%= f.submit 'Apply changes', class: 'btn btn-large btn-primary' %>
<% end %>
</div>
</div>
I think that the error is in this view (Projects/edit):
<%= f.fields_for :requested_roles do |builder| %>
ciao
<%= render 'requested_role', :f => builder %>
<% end %>
this code, even without the partial, lead to a N-times repeated requested_roles. In fact, without the partial _requested_role, we have N "ciao", but we should have only one.
projects/_requested_role.html.erb
<% if #project.requested_roles.any? %>
<p>Modifica ruoli richiesti </p>
<%end%>
<%= #project.requested_roles.count %>
<% for requested_role in #project.requested_roles %>
<div class="fields">
<p>
<p>Requested role: <%= role_to_string(requested_role.role) %></p>
<%= f.label :role, "Modify role" %>
<%= f.select :role, options_for_select([["Regista",1],["Sceneggiatore", 2],["Direttore della fotografia", 3], ["Operatore",4],
["Fonico", 5], ["Montatore", 6], ["Truccatrice",7], ["Costumista",8], ["VFX Artist",9],
["Produttore", 10], ["Attore",11], ["Attrice",12], ["Grip/Runner",13]], :selected => requested_role.role) %>
<%= link_to_remove_fields "remove", f %> #dinamically remove a field
</p>
<% end %>
</div>
Can you help me please? I can't figure out where the error is. Thank you in advance.
The other problem is related to the links to dinamically delete and add requested_roles (javascript-jquery).
If I have 3 requested_roles (9 select fields instead of 3 because of the error that I mentioned before) and I delete (through link_to_remove_fields) the last one there's no problem. But if I delete the first one, the fields and even the submit button below it disappear and I can't modify the roles or submit the changes.
When I add (through link_to_add_fields) a new role and I already have, for example, 2 requested_roles (Director, Producer), when I click on the link to add the new requested_role another bug occurres. Instead of a select field to choose the role, a copy of the 2 existing select fields (Director, Producer) appears.
application_helper.rb
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize, :f => builder)
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
Application.js
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));
}
I can't understand what goes wrong. If you have some idea can you give me some advice? Thank you very much.
Dario
The problem is that you're iterating twice.
<%= f.fields_for :requested_roles do |builder| %>
ciao
<%= render 'requested_role', :f => builder %>
<% end %>
Will automatically repeat the requested_role partial for each requested role. That's why it shows "ciao" N times, because that's what fields_for does at render. You probably need to read the doc to understand how it works: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
So there is no need to have
for requested_role in #project.requested_roles
in your partial. It will only repeat all requested roles each time fields_for renders it. Here's what your code should look like in your edit.html.erb :
<% if #project.requested_roles.any? %>
<p>Modifica ruoli richiesti </p>
<%end%>
<%= #project.requested_roles.count %>
<%= f.fields_for :requested_roles do |builder| %>
<%= render 'requested_role', :f => builder %>
<% end %>
<p><%= link_to_add_fields "Add requested role", f, :requested_roles %></p>
And the requested_role partial should simply be:
<div class="fields">
<div>
<p>Requested role: <%= role_to_string(f.object.role) %></p>
<%= f.label :role, "Modify role" %>
<%= f.select :role, options_for_select([["Regista",1],["Sceneggiatore", 2],["Direttore della fotografia", 3], ["Operatore",4],
["Fonico", 5], ["Montatore", 6], ["Truccatrice",7], ["Costumista",8], ["VFX Artist",9],
["Produttore", 10], ["Attore",11], ["Attrice",12], ["Grip/Runner",13]], :selected => f.object.role) %>
<%= link_to_remove_fields "remove", f %>
</div>
</div>
Fixing your partial should fix your second problem with the links.
You might want to consider using Ryan's gem for nested_forms
https://github.com/ryanb/nested_form

Rails form_tag unknown format error as js format with remote: true

I'm trying to add a form to a modal and then submit the form via JS format with remote: true but the form seems to be submitted as HTML instead, causing an unknown format issue. Any help would be appreciated.
Started POST "/create_deliv_extra" for 127.0.0.1 at 2014-06-16 20:38:17 -0400
Processing by DeliveriesController#create_deliv_extra as HTML
Completed 406 Not Acceptable in 21ms
ActionController::UnknownFormat
Form:
</br>
<%= form_tag create_deliv_extra_url, remote: true, class:"form-inline mb10 mt5", id:"extra_f_#{order.id}" do %>
<%= text_field_tag :description, #extra.description, placeholder: "Description", "data-provide"=>"typeahead", autocomplete: :off, "data-source"=>"#{Extra.all.pluck(:description).uniq}", class:"span4" %>
<% if order.cod == true || current_user.role == "Billing" || current_user.role == "admin" || current_user.role == "Exec" %>
<div class="input-prepend">
<span class="add-on">Amount $</span>
<%= text_field_tag :amount, #extra.amount, placeholder: "$000.00", class:"input-xs" %>
</div>
<% end %>
<div class="input-prepend">
<span class="add-on">Quantity</span>
<%= text_field_tag :quantity, #extra.quantity.present? ? "%g" % #extra.quantity : 1, class:"input-xxs" %>
</div>
<% next_d = order.deliveries.present? ? order.deliveries.maximum(:delivery_counter) + 1 : 1 %>
<div class="input-prepend">
<span class="add-on">From</span>
<%= text_field_tag :load_start, next_d, class:"input-xxxs" %>
</div>
<div class="input-prepend">
<span class="add-on">To</span>
<%= text_field_tag :load_end, next_d, class:"input-xxxs" %>
</div>
<%= select_tag :extra_type, options_for_select(["Per Yard","Per Load","Flat Fee"], #extra.extra_type), class:"input-small" %>
<%= hidden_field_tag :order_id, order.id %>
<%= hidden_field_tag :truck_id, #id %>
<%= button_tag "Add", class:"btn btn-danger" %>
<% end %>
Controller:
def create_deliv_extra
#order = Order.find(params[:order_id])
#id = params[:truck_id]
#extra = Extra.create(amount: params[:amount], extra_type: params[:extra_type], order_id: params[:order_id], description: params[:description], quantity: params[:quantity], load_start: params[:load_start], load_end: params[:load_end])
#extras = #order.next_deliv_extras.length > 1 ? "Extras: " + #order.next_deliv_extras : "No Extras"
respond_to do |format|
format.js
end
end
I've also tried adding format: :js in the form_tag but still receive the same error.
I know the question is old, but I got the same problem and found out my application.js was not requiring jquery_ujs. I added it to my application.js file:
//=require jquery
//=require jquery_ujs
Now remote links and forms work as expected :)
I believe your problem may stem from a form_tag being with another form (form_tag, form_for, or html form). If this is the case, just find a way within the html for the first form to begin and end and then start the second form after the first ends.
<%= form_for do %>
...
<%= button_tag "#" %>
<% end %>
<%= form_tag create_deliv_extra_url, remote: true, class:"form-inline mb10 mt5", id:"extra_f_#{order.id}" do %>
...
<%= button_tag "Add", class:"btn btn-danger" %>
<% end %>

Nicedit works localhost but not Heroku

I have troubles with nicEdit.
Framework is ruby 2.0.0 / rails 4.0.1
When in localhost, works but only if you upload the page twice.
But when deploy in Heroku, it does not work at all.
I followed this example up to the line.
I have a niEdit.js under ../vendor/assets/javascripts
Here is my full form:
<%= javascript_include_tag 'nicEdit' -%>
<%= simple_form_for(#recipe) do |f| %>
<%= f.error_notification %>
<div class="field">
<%= f.label "Elige un cromo" %><br />
<%= f.file_field :chrome %>
</div>
<div class="form-inputs">
<%= f.association :user, label_method: :name, collection: User.where(name: current_user.name), :label => "Cociner#" %>
<%= f.association :category, :label => "Categoría", label_method: :plato_category, collection: Category.all %>
<%= f.input :plato %>
<%= f.input :minutos %>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<div class="well well-small">
<p>Tejemaneje</p>
<%= f.text_area :tejemaneje, :rows => 10, :style => 'width: 700px' %>
</div>
</div>
<p>
</p>
<%= f.button :submit, "Receta", :class => "btn btn-success" %>
<% end %>
What should I do different for it to work fully both on localhost and heroku? Thanks.
PARTIAL SOLUTION:
I moved nicEdit.js under /assets/javascript and the script is now running, but it does not matter if inside NicEdit.js this line is
iconsPath : '/assets/nicEditorIcons.gif' and the icons under /assets/images/nicEditorIcons.gif, they do not display. The same for /assets/nicEditorIcons.gif
I moved the icons under /assets/javascripts and change the line to
iconsPath : '.../nicEditorIcons.gif'
And I also tryed to put the icons under /assets/nicEditorIcons.gif with the icons ther. Nothing works.
Does Heroku have a special place for icons? Do I have to change the script call? Any help?

Clear a text_field after create w/o refresh

Right now I'm using AJAX for creating comments. However when I hit enter the textfield remains populated. I want the field to refresh (and still be able to write in another comment). no errors but it still doesn't refresh the textfield it seems. The create part works fine.
create.js/erb: (need to fix the second line here so that it fully replaces)
$('#<%= dom_id(#micropost) %>').html("<%= escape_javascript(render(:partial => #micropost.comments))%>")
$("#comment_field_<%=#micropost.id%>").replaceWith("<%= escape_javascript(render 'shared/comment_form', micropost: #micropost) %>")
Microposts/_micropost:
<span id="<%= dom_id(micropost) %>"><%= render micropost.comments %></span>
<span id="comment_field_<%=micropost.id%>"><%= render 'shared/comment_form', micropost: micropost if signed_in? %></span>
Shared/Comment_form:
<%= form_for #comment, id:"comment_form", remote: true do |f| %>
<%= hidden_field_tag :micropost_id, micropost.id %>
<div id="comment_field">
<%= link_to gravatar_for((current_user), size: 29) %>
<%= f.text_field :content, placeholder: "Say Something...", id: "comment_text_field", :style => "width: 508px; text-indent: 5px" %>
</div>
<% end %>
Needed to only use jquery to clear the text_field by setting empty value
create.js.erb
$("#comment_text_field_<%=#micropost.id%>").val("")
best practice to use a unique dynamic ID but probably would have worked either way.
Shared/Comment_form:
<%= f.text_field :content, id: "comment_text_field_#{micropost.id}" %>

Categories

Resources