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

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);

Related

Appending a form in jQuery

Im trying to append a form_for to a div with no luck, I've been through everything in the javascript console inside the div that holds the form but can't seem to find the contents to target. Please let me know if this is hard to understand and i'll try to explain myself better. I have also tried
$('.admin-right-content').innerHTML = "<%= render 'products/add_products' %>"
$(".admin-right-content").append("<%= escape_javascript(render(:partial => #add_products) %>");
$(".admin-right-content").append("<%= escape_javascript(render(:partial => add_products) %>");
$(".admin-right-content").append("<%= escape_javascript(render add_products %>");
$('.admin-right-content').append($('.add-products-form'))
The list goes on and on.
I'm a newbie to Rails, so apologies if this turns out to be something simple or some silly mistake on my end.
The partial containing the form is _add_products.html.erb.
Instead of printing the form out its actually appending the code to the div.
<div class="add-products-form">
<%= form_for #product do |form| %>
<%= form.label 'Product name' %>
<%= form.text_field :product_name %>
<%= form.label 'Type'%>
<%= form.text_field :type %>
<%= form.label 'Price' %>
<%= form.text_field :price %>
<%= form.label 'Description' %>
<%= form.text_area :description %>
<%= form.label 'Add photos' %>
<%= form.data_field :photos %>
<%= form.submit "Submit" %>
<% end %>
</div>
You can try this:
$('.admin-right-content').append($('.add-products-form').children().clone())

Rails 4 render js: redirecting to another page and displaying raw js

In my TestimoniesController I have written a render js: line in the event that #testimony.save is not successful.
if #testimony.save
redirect_to #testimony
else
render js: "alert('Please make sure you feel out every field of the Testimonial!');"
end
Instead of rendering the alert that I write, it redirects me to the /testimonies route and just displays the string that was supposed to be rendered as javascript and nothing else. Is my JS disabled somehow?
Here is my new.html.erb file:
<h1> New Testimonial</h1>
<%= form_for :testimony, url:testimonies_path do |f| %>
<p>
<%= f.label :first_name %><br>
<%= f.text_field :first_name %>
</p>
<p>
<%= f.label :last_name %><br>
<%= f.text_field :last_name %>
</p>
<p>
<%= f.label :email %><br>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :contact_number %><br>
<%= f.text_field :contact_number %>
</p>
<p>
<%= f.label :country %><br>
<%= f.text_field :country %>
</p>
<p>
<!--bunch of the same stuff -->
<p>
<%= f.submit %>
</p>
<% end %>
In order tor respond with js, you have to add remote: :true in your form_for, and submit your request as ajax
<%= form_for :testimony, url:testimonies_path, remote: :true do |f| %>
but then your
redirect_to #testimony
will not work as it only works on html format, so in that scenario replace this line with
render js "location.href = '#{testimony_path}'";

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}" %>

Dynamically add & remove new but the same fields of a form any amount times

I have a form that has no nested models.
class UserProductsController
def new
#user_product = current_user.user_products.build
end
end
With jquery/javascript i want to add and remove new #user_product fields on the same form. This how it would look normally:
<%= form_for(#user_product) do |f| %>
<%= f.error_messages %>
<%= f.text_field :product %>
<%= f.text_field :address %>
<%= f.text_field :price %>
<%= f.submit %>
<% end %>
And I'm trying to achieve:
<%= form_for(#user_product) do |f| %>
<%= f.error_messages %>
<%= f.text_field :product_name %>
<%= f.text_field :address %>
<%= f.text_field :price %>
---New ID(New generated ID, could be any new number in the database)
<%= f.text_field :product_name %>
<%= f.text_field :address %>
<%= f.text_field :price %>
<%= Remove this Product %> # ajax style, this link removes this product entirely
----ID 3----
<%= f.text_field :product_name %>
<%= f.text_field :address %>
<%= f.text_field :price %>
<%= Remove this Product %>
-----Add link------
<%= Add Another Field %> # ajax style adding
<%= f.submit %>
<% end %>
Notice the new IDs that aren't preset and the one submit button so this way more then one Product can be created at a time by a User. How do i achieve the above?
Thank you.
Answer:
Using the User.rb model you can do what James said. Here is my form that works.
<%= form_for(current_user, :url => user_products_path) do |f| %>
<%= f.error_messages %>
<%= f.fields_for :user_products do |builder| %>
<%= render "user_product_fields", :f => builder %>
<% end %>
<%= link_to_add_fields "Add a UserProduct", f, :user_products %>
<%= f.submit "Create" %>
<% end %>
_user_product_fields.html.erb
<div class="fields">
<%= f.label :product, "Product" %>
<%= f.text_field :product %>
<%= f.label :address, "Address" %>
<%= f.text_field :address %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= link_to_remove_fields "remove", f %>
</div>
As others have suggested (somewhat unhelpfully), use nested forms.
You need the form to be based on the current_user object with fields_for declaration for :user_products. You will need to set the url for the form to post back to the user_product controller not the user controller using url_for and you will need to adjust the user_product controllers update and create actions to make use of params[:user] instead of params[:user_product]
If you have your accepts_nested_attributes configured properly all should be good.
BTW if you follow those railscasts you will find that the javascript to add new will not work for Rails 3.x
You should use something like this for your view helpers
module ApplicationHelper
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 + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')")
end
end
and something like this for your javascript in your application.js file
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).up().insert({
after: content.replace(regexp, new_id)
});
}
and obviously your form_for need to be refactored to something like this
<%= form_for(current_user, :url => user_product_path) do |f| %>
<!-- add your f.fields_for :user_products here, probably in a rendered partial -->
<%end%>
That should be enough with the rails casts to get you going
Checkout this:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
You can use cocoon for this.

Categories

Resources