Ajax request returns (406 Not Acceptable ) - ruby-on-rails

In my Rails app javascript template profile.js.erb don't get rendered. I get error code 406 Not Acceptable. This template is supposed to append a partial in a view star#profile. Ajax request is made by jquery infinite scroll plugin. Here is my code
.
action
def profile
#page=params[:page] ||1
#videos=Video.all(:page=>#page)
respond_to do |format|
format.js
format.html
end
end
view Stars#profile
<div id="content">
<div class="post">
<%=render 'videos'%>
</div>
profile.js.erb
$('div.post').append("<%=escape_javascript(render 'videos')%>");
routes
match "stars/profile/:page"=> "stars#profile", :via => :get
log in console
Started GET "/stars/profile?page=2" for 127.0.0.1 at 2013-06-20 00:05:58 -0500
Processing by StarsController#profile as application/JavaScript
Parameters: {"page"=>"2"}
Completed 406 Not Acceptable in 65836ms
Ajax setup
jQuery.ajaxSetup({
'beforeSend': function(xhr, settings) {
xhr.setRequestHeader("Accept", "application/javascript");
var token=$('meta[name="csrf-token"]').attr('content');
xhr.setRequestHeader('X-CSRF-Token',token );
settings['dataType'] = "javascript";
settings['contentType'] = "application/javascript";
}
});

From the log:
GET "/stars/profile?page=2" does not include .js after profile. So rails does not handle it at javascript.
GET "/stars/profile.js?page=2" should be the call..

Related

Rails form_with (remote) does not see existing template

A rails form that posts
<%= form_with url: search_results_labours_path do |f| %>
gets processed by the controller, but fails to return the expected XHR response with
Started POST "/labours/search_results" for ::1 at 2021-02-12 10:12:46 +0100
Processing by LaboursController#search_results as JS
[...]
ActionController::UnknownFormat (LaboursController#search_results is missing a template for
this request format and variant.
request.formats: ["text/javascript", "*/*"]
request.variant: []):
Yet, the template does exist
and it calls a partial _search_results.html.erb
$("div#search_results").html("<%= j render ('labours/results') %>").css({ opacity: 0 }).fadeTo('slow',1);
def search_results
#labours = Labour.order(usercontract_id: :asc).where('time_start >= ?', params[:labour][:date_start].to_date.at_beginning_of_day ).all
index_personnel
end
Why does rails not see the template for that action?
Update
changing the form to a remote
<%= form_with(url: search_results_labours_path, local: true) do |f| %>
and processing the partial as a non partial search_results.html.erb processes entirely as expected, confirming the problem is in perceiving the existence of search_results.js.erb The file also appears, with this spelling via the console to list all files.
-rw-r--r--# 1 deploy staff 105 12 Feb 10:10 search_results.js.erb

Strange Routing Behavior in Rails on Image Upload Using Carrierwave

I'm working on creating a new edit/update view and routes for a fairly large Rails (v4.0.3) app. I'm using remote: true to submit sections of the form without reloading the whole page, and then simply replacing the form HTML with the response HTML (which is the form partial). The URL (.../edit) should remain the same.
It works fine to update text fields, but when I upload an image (using Carrierwave) I get this strange behavior where the image uploads fine but then I get redirected to the controller action URL (.../update) and the browser displays the raw partial out of context.
Here's the relevant method from my resource controller:
def update
respond_to do |format|
if #provider.update_attributes(admin_provider_params)
if params[:provider][:logo]
#provider.logo = params[:provider][:logo]
#provider.save
elsif params[:provider][:remove_logo] == '1'
#provider.remove_logo!
#provider.save
end
format.html { render partial: "provider_form", locals: { provider: #provider } }
format.json { render json: #provider }
else
format.html { render action: "edit" }
format.json { render json: #provider.errors, status: :unprocessable_entity }
end
end
end
And here's some selected code from my view partial:
= simple_form_for [:admin, #provider],
remote: true,
html: { class: 'form-horizontal', multipart: true, id: 'provider-data-form' },
authenticity_token: true,
wrapper: :horizontal_form do |f|
-# (SOME OTHER FORM FIELDS HERE)
-# LOGO UPLOAD ELEMENTS
.form-group.file.optional.provider_logo
= f.input :logo, input_html: { id: "provider-logo-upload-real", class: "hidden"}, :as => :file, wrapper: false
%button#provider-logo-upload-btn= #provider.logo_url.nil? ? "Upload Logo" : "Replace Image"
%img#logo-upload-img{src: #provider.logo_url}
-# SUBMIT FORM
= f.button :submit, translate_helper(:save), id: "save-provider-form-btn"
:javascript
$(document).ready(function() {
// Handle logo upload via proxy button
$('#provider-logo-upload-btn').on("click", function(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
$('#provider-logo-upload-real').click();
});
// Preview logo before upload
$('#provider-logo-upload-real').change(function(e) {
$('#logo-upload-img').attr("src", URL.createObjectURL(event.target.files[0]));
});
// Handle Form submit
$('#provider-data-form')
.on("ajax:success", function(evt, data, status, xhr) {
console.log("AJAX Success!", arguments);
// On success, refresh just the provider form partial
$('#provider-data-form').replaceWith(xhr.responseText);
});
});
I think this is all the relevant code, but I'm happy to provide more on request. There's not much additional logic tacked on the CarrierWave Uploader classes.
Finally, here are my server logs (edited slightly for brevity) when I submit the form with a new image for upload:
I, [2016-10-17T10:09:24.745387 #1219] INFO -- : Started PATCH "/en/admin/providers/8" for 127.0.0.1 at 2016-10-17 10:09:24 -0400
I, [2016-10-17T10:09:24.754005 #1219] INFO -- : Processing by Admin::ProvidersController#update as JS
I, [2016-10-17T10:09:24.754133 #1219] INFO -- : Parameters: application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01", "locale"=>"en", "id"=>"8"}
I, [2016-10-17T10:09:24.754187 #1219] INFO -- : Parameters: {
// LISTS PARAMETERS, INCLUDING IMAGE UPLOAD DATA
}
I, [2016-10-17T10:09:25.105809 #1219] INFO -- : Rendered admin/providers/_provider_form.html.haml (52.9ms)
I, [2016-10-17T10:09:25.106381 #1219] INFO -- : Completed 200 OK in 352ms (Views: 43.8ms | ActiveRecord: 51.8ms)
// IF NO IMAGE WAS INCLUDED, NORMALLY IT STOPS AT THIS POINT, BUT...
I, [2016-10-17T10:09:25.111315 #1219] INFO -- : Started PATCH "/en/admin/providers/8" for 127.0.0.1 at 2016-10-17 10:09:25 -0400
I, [2016-10-17T10:09:25.122752 #1219] INFO -- : Processing by Admin::ProvidersController#update as HTML
I, [2016-10-17T10:09:25.122925 #1219] INFO -- : Parameters: {
// LISTS PARAMETERS, NO IMAGE UPLOAD DATA
}
I, [2016-10-17T10:09:25.268027 #1219] INFO -- : Rendered admin/providers/_provider_form.html.haml (43.9ms)
I, [2016-10-17T10:09:25.268360 #1219] INFO -- : Completed 200 OK in 145ms (Views: 35.2ms | ActiveRecord: 39.5ms)
// PAGE DISPLAYS PARTIAL ONLY, URL IS FOR UPDATE ROUTE RATHER THAN EDIT
Sorry for such a long question; I've been puzzled by this for over a week. I'd appreciate any help I can get!
I guess that is because Rails remote form with file falls back to HTML submission instead of regular JS submission . Try using remotipart Gem.
Okay, I think I've been able to solve it. Thanks to #sajan, I found this issue on the Remotipart github page: https://github.com/JangoSteve/remotipart/issues/129
By preventing default on my submit button click events and then submitting the form itself, I was able to stop the multiple form submit issue.

Why the destroy/delete link dees not work?

I am stuck at Delete/Destroy. Any help would be appreciated!
I am using Ruby 2.0.0 and Rails 3.2.6 on Mac 10.8.3 with Postgres.
This is the delete link which supposed to work:
<%= link_to 'Destroy', #product, method: :delete, data: { confirm: 'Are you sure?' } %>
But when I click on the Destroy link it directs me to the user's profile. I don't get any confirmation window and no action is done (delete). It seems it is just stayed at the same page. I am using Firefox but in IE and Chrome are the same.
This is what I have:
the gem "jquery-rails" is installed
applications.js (from app/assets/javascripts) has these lines:
//= require jquery
//= require jquery_ujs
//= require_tree .
application.html.erb (from app/views/layouts) has these lines:
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
In view source I see:
<script src="/assets/application.js?body=1" type="text/javascript"></script>
<meta content="authenticity_token" name="csrf-param" />
<meta content="MVlJi+WJE1cwWoHnBrpRWIa13gqio0iPT3IL6kpQYdE=" name="csrf-token" />
in products_controllers.rb (from app/controllers) I have:
def destroy
#product = Product.where(:id => params[:id]).first
#product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :no_content}
end
end
in routes.rb (from config) I have:
resources :products
What is wrong with that Destroy link?
On the same RoR project the Edit link works fine.
So, why the link doesn't work? Is it a Javascript problem or some other problem which I am not seeing?
And here is the server's log: (It seems the "delete" action does not been executed)
Started GET "/products/9" for 127.0.0.1 at 2013-08-01 20:01:08 -0500
Processing by ProductsController#show as HTML
Parameters: {"id"=>"9"}
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = 9 LIMIT 1
Rendered products/show.html.erb within layouts/application (0.5ms)
Completed 200 OK in 27ms (Views: 25.8ms | ActiveRecord: 0.1ms)
One helpful way to handle path issues with Rails is to type "rake routes" in your console, in order to have a list of all the paths available to play with your ressources.
By declaring "resources :products" in your routes.rb file, "rake routes" will provide a list of Prefix/Verb/URI Pattern/Controller#Action for this particular resource. You will have something like:
Prefix Verb URI Pattern
product GET /product/:id(.:format) product#show
PATCH /product/:id(.:format) product#update
DELETE /product/:id(.:format) product#destroy
Take the word of the prefix column (product), add _path to this word (product_path), use the correct method (DELETE), pass the ids as parameters (in this case, you can just do product_path(#product)), and you're done. You will have :
<%= link_to "Delete", product_path(#product), method: :delete, data: { confirm: "Are you sure?" } %>
Perhaps (I'm just guessing, but one day I ran into a similar problem) if you design catalog or shop with a shopping cart based on the book Agile Web Development with Rails, the product model may contain a filter before_destroy :ensure_not_referenced_by_any_line_item that prevents the product from destroy in case if product listed in LineItems. If this is your case, you can clear list of LineItems in the ProductsController before destroying the product. Otherwise sorry.

Ajax calls in rails when jquery.js included don't work

I'm using Rails 2.3.8.
In my application.rhtml I have:
<%= javascript_include_tag "jquery.js"%>
And in my index.rhtml which uses application.rhtml for a layout I have:
<div id="search_residential"> <%= link_to "Residential",
"javascript:residentialSearchForm()", :onclick=> remote_function(:url => {:propertyType => 'residential', :controller => 'site', :action => 'searchform'}, :update => 'search_form', :method => :get)%></div>`
In my partial that should be rendered I have:
<%logger.debug "Residential Form Partial Rendered"%>
When I click the link my log outputs:
Processing SiteController#searchform (for 127.0.0.1 at 2012-10-05 11:11:02) [GET]
Parameters: {"controller"=>"site", "propertyType"=>"residential", "action"=>"searchform", "authenticity_token"=>"Iw3ID/4Lh5IReUwOnhhSUXfn2IIVUnYpqG1N7DE4BHg="}
Rendering site/searchform
Residential Form Partial Rendered
Rendered site/searchbar/_search_residential (5.2ms)
Rendered site/searchbar/_search_form (5.9ms)
Completed in 9ms (View: 7, DB: 0) | 200 OK [http://localhost/site/searchform?propertyType=residential&authenticity_token=Iw3ID%2F4Lh5IReUwOnhhSUXfn2IIVUnYpqG1N7DE4BHg%3D]
But nothing is shown on the website. If I remove the include for jQuery then the partial is rendered.
remote_function is a prototype helper and depends on prototype.js
Jquery would be conflicting at the $ namespace. Its advisable to not use prototype helpers.
Or You should initialize jquery in a noConflict mode.

Error during failsafe response: Ruby on Rails 3

I have a form_tag that works fine using html, but when I use ajax with the remote => true I am getting this error:-
My terminal log shows:-
Started GET "/" for 127.0.0.1 at 2010-11-01 01:19:49 +0000
Processing by HomepagesController#index as HTML
Homepage Load (0.6ms) SELECT "homepages".* FROM "homepages"
Rendered homepages/index.html.erb within layouts/application (23.0ms)
Completed 200 OK in 40ms (Views: 27.3ms | ActiveRecord: 0.6ms)
Error during failsafe response: incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string)
* then a load of cleaner.rb stuff
then:-
Started GET "/homepages?utf8=%E2%9C%93&search=hom" for 127.0.0.1 at 2010-11-01 01:19:56 +0000
Processing by HomepagesController#index as JS
Parameters: {"utf8"=>"✓", "search"=>"hom"}
Homepage Load (0.5ms) SELECT "homepages".* FROM "homepages" WHERE (section LIKE '%hom%')
Rendered homepages/index.js.erb (2.9ms)
Completed in 19ms
In my index.js.erb I have:-
$("testsearch").update("<%= escape_javascript(render(#homepages))%>");
and in my Controller I have:-
def index
#homepages = Homepage.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #homepages }
format.js { render :layout => false }
end
in my view I have:-
which prints #homepages using a table using <% #homepages.each do |homepage| %> which is not being updated.
Anyone have any ideas as to why I get this error.
I have cracked it by going onto an IRC chat room (irc.freenode.net RubyonRails) and a ProjectZen (human being somewhere out there in the ether) helped me to get it working.
Apparently what was happening was that I was following Ryan Bates who does many extremely good Railcast videos, but he builds on previous Railcast. Therefore in his 205 Railscast, which deals with Ajax calls, he did not mention that you must have:-
format.js in the action in the controller.
His xxxx.searchxxxxx needs to be created in the controller or model.
And that when I did :-
<%= render(#homepages)%> <!-- (in his case <%= render(#products)%>) -->
The render was looking for a partial called "_homepage" (not "homepages") (I did not even have a partial therefore I got the UTF8 to ASCII error).
And then in "_homepage" I would add my code to render the results.
What I have now done in my index.html.erb is to put <%= render(#homepages)%>, in the (div id = testsearch) in place of the code I use to render #homepages and then place that code in a partial "_homepage". Now I can use "_homepage" for the html and the Ajax call.
At the moment I have a slight problem in that it is rendering all the data in the"#homepages" as many times as the number of records. At the moment I do not know why, but at least the Ajax call is working.

Resources