I'm trying to implemet a complex task, and faced with a problem, that my JS code do not work when called from format.js.
I have a link with such code:
= link_to new_user_support_letter_path, {:id => 'contact-us', :remote => true }
In my user_support_letters_controller.rb:
def new
#letter = UserSupportLetter.new
respond_to do |format|
format.js {}
format.html
end
end
In new.js.erb:
alert("rrr");
So, when I click a link nothing happens.
Meaningful logs for clicking a link:
I, [2016-10-19T21:47:41.130608 #1] INFO -- : Started GET "/user_support_letters/new" for 172.18.0.6 at 2016-10-19 21:47:41 +0000
I, [2016-10-19T21:47:41.150411 #1] INFO -- : Processing by UserSupportLettersController#new as JS
I, [2016-10-19T21:47:41.269853 #1] INFO -- : Rendered user_support_letters/new.js.erb within layouts/application (0.1ms)
I, [2016-10-19T21:47:41.344629 #1] INFO -- : Rendered application/_support_email.slim (0.1ms)
...
Can anybody tell what I'm doing wrong? Thanx!
To get this to work you need to set layout to false and declare the content_type you're using.
From what I know/have read this is standard behaviour in rails. Here is a similar post discussing it with a link to a bug log. https://stackoverflow.com/a/1170121/3366016
Change your controller action to this:
def new
#letter = UserSupportLetter.new
respond_to do |format|
format.js { render layout: false, content_type: 'text/javascript' }
format.html
end
end
By default it will try to load in the current layout for the given content type. For JS it typically is smart enough to know not to load a layout. By setting false you are disabling the layout and just telling it to render without a layout.
It seems if you are using some form of templateing it messes with the requests a bit. This answer seems to identify in the comments a specific work around for slim template. This answer describes another solution, basically using the default layout setup. With this, Rails seems to know how to handle it for JS requests.
Related
I have an issue. I had a freelancer do some things with my code and he messed up some things. One of the main things is the pagination doesn't work. I checked my old files and it used to say this
Processing by HomeController#load_more_books as JS
Now it's giving me
Processing by HomeController#load_more_books as JSON
How do I change the processing back to Javascript? Thank you
Change the default format in your routes
get "/some-resource", to: "some_controller#some_method", defaults: {format: "js"}
or in you controller you can tell .json requests to respond to .js
#app/controllers/some_controller.rb
class SomeController
def some_method
respond_to do |format|
format.json { render "some_js_template.js" }
end
end
end
I've been following http://blog.markhorgan.com/?p=522 as a guide to update an image in a form with an ajax callback. Image saves fine but I want to do some clever ajax so the page doesn't refresh.
Here's my code:
edit.html.haml:
#promo-image
= render partial: 'promo_image'
_promo_image.html.haml:
= form_for( #property, remote: true) do |f|
= f.file_field :promo_image, :pattern => "^.+?\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$", :id => 'promo-image-upload'
= f.submit 'Update'
= image_tag #property.promo_image.url(:medium)
properties_controller.rb
def update
#property = Property.find(params[:id])
if #property.update(property_params)
format.js
else
render 'edit'
end
end
update.js.haml:
$("#promo-image").html("#{escape_javascript(render partial: 'promo_image',)}");
With the code outlined above I get error pointing to the format.js line:
ArgumentError in PropertiesController#update too few arguments
Can anyone see where I'm going wrong or perhaps point me in the right direction?
Many thanks!
Steve
UPDATE
Just to be clear, I want to be able to update JUST the Div stated here:
update.js.haml:
$("#promo-image").html("#{escape_javascript(render partial: 'promo_image',)}");
This code works, but refreshes the whole page:
respond_to do |format|
format.html { redirect_to edit_property_path(#property) }
format.js
end
FURTHER UPDATE
Just to be clear on my motives, I want to be able to update an element on the edit page, and not be redirected to a different one, e.g. show or index. This is for UI reasons. The guide above talks about the exact same thing.
FINAL UPDATE
The issue is because I'm using a file upload, this can't be achieved via ajax. For those in a similar situation see here: Rails form_for with file_field and remote => true and format => :js
A solution could lay here, and I will investigate this: https://github.com/JangoSteve/remotipart
Thanks to everyone for helping me work out the error of my ways!
Regarding your first update, you said that this code works, but refreshes the page:
respond_to do |format|
format.html { redirect_to edit_property_path(#property) }
format.js
end
If that is the case, that means the incoming request is an html request, rather than an AJAX request. So the format.html block runs and redirects the browser to the same page, which now has the updated image.
What you need to do is figure out why the page is not sending the request as AJAX. You can see the request format if you look at the terminal output (if running locally). It will say something like:
Processing by ControllerName#action as [format]
Format needs to be JS in order for the format.js to render update.js.haml.
UPDATE:
Now that you mention it, the issue is indeed the file_upload field. Uploading files with AJAX is actually not possible with the Forms Helper. See the docs:
Unlike other forms making an asynchronous file upload form is not as simple as providing form_for with remote: true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
I did a quick search on Google and found the remotipart gem, which seems to specialize in doing this. I don't have any experience with it though, so you're on your own from here on. :)
Try changing your update action to
def update
#property = Property.find(params[:id])
if #property.update(property_params)
respond_to do |format|
format.html { redirect_to properties_path }
format.js
end
else
render 'edit'
end
end
Source
I'm making an e-mail service with mailboxer gem.
In my index view I have several links that will lead to inbox/draft... like this:
<%= link_to "Inbox", show_conversations_path, :remote => true %>
...
<div id="content">
</div>
Then my show_conversation js.erb
$("#content").html("<%=escape_javascript(render :partial=>"show_conversations")%>");
the controller (messages_controller)
def show_conversations
#inbox = current_user.mailbox.inbox
respond_to do |format|
format.js
end
end
And there's also a partial view _show_conversations.html.erb (already tested, through a simple render so no errors there).
So my problem is that, when I click on the link, it actually redirects to a blank plage (when it shouldnt, or at least it's not my intention, redirect at all, just show the content on the div).
I've realized that it actually renders its controller, then the erb.js, the partial view, and I Don't know why the controller again but this time as HTML.
A piece of the log:
Started GET "/en/messages/show_conversations"4
Processing by MessagesController#show_conversations as JS
...
Rendered messages/_show_conversations.html.erb (7962.4ms)
Rendered messages/show_conversations.js.erb (23239.0ms)
Completed 200 OK in 23330ms (Views: 23237.9ms | ActiveRecord: 5.0ms)
Started GET "/en/messages/show_conversations
Processing by MessagesController#show_conversations as HTML
Completed 406 Not Acceptable in 8ms (ActiveRecord: 0.5ms)
I know it shouldn't redirect, and I believe it shouldn't call two times to the controller (and the second one as if it was html instead of js), but I don't really know why it's happening nor have I found a similar problem through the forum
Check with below code, if it works
def show_conversations
#inbox = current_user.mailbox.inbox
respond_to do |format|
format.js { render :layout => false }
end
end
Try modifying this line:
$("#content").html("<%=escape_javascript(render :partial=>"show_conversations")%>");
to:
$("#content").html("<%= escape_javascript(render :partial=>'show_conversations') %>");
or make it pretty:
$("#content").html("<%= j render :partial=>'show_conversations' %>");
I am building a form in rails that will edit an existing question via ajax.
After the form is submitted and the question has been updated, the update method in the controller renders update.js.erb, which will hide the form again.
My problem is that the javascript code in update.js.erb is not executing at all.
I know that the file is rendering because it shows up in the server output, and when I put a
<% raise params %>
into it, it works.
However, even the simplest
alert('hello');
has no effect in the same file.
I've ruled out javascript and jquery configuration issues because the same code works perfectly in my edit.js.erb file. It's just not working in update.js.erb.
What am I missing?
Edit:
Firebug shows no errors. Here is the response in firebug's network panel:
alert('hello');
$('#question_body').replaceWith('<h4><p>jhsdfjhdsb k jdfs j fjfhds <strong>jfshaflksd;hf sdldfs l fdsalkhdfskhdfs</strong>;fd lfdksh hfdjaadfhsjladfhsjadfs ;df sjldfsj dfas hafdsj fdas ;ldfas ldfs df dl;hdf fdh ;fdj ;lfads</p></h4>');
def update
Edit 2:
This is the controller action:
def update
respond_to do |format|
if #question.update_attributes(params[:question])
format.html { redirect_to #question, :flash => { :success => 'Question was successfully updated.' } }
format.json { head :no_content }
format.js {}
else
format.html { render action: "edit" }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
In your $.ajax call make sure to set the dataType option to "script" otherwise the response could be interpreted in other ways and thus not executed as JS.
Do you work with haml, or html.erb? If the former, then this might be the solution:
respond_to do |format|
...
format.js {render layout: false}
end
I had the exact same problem, found this question early on, took another hour or so of Googling to find this question on StackOverflow that led me to it: jQuery + Ajax + Haml. js.erb files not firing
In your update.js.erb file you need to escape javascript wherever you execute ruby code.
$('.container').empty().append('<%=
escape_javascript(
render 'update'
)
%>')
This is what solved it for me ...
This issue isn't just because of Controller side. It is also can be in the View side which is you didn't clarify the data-type of your post request.
Make sure in your console that the request is treated as JS.
Reference: Similar issue
I ran into the same issue and found this page. I tried methods listed here but found no luck. While later the following method solve my issue.
My originally code was:
$('#html_id').html('<%=#ruby_variable%>');
And I updated it to:
$('#html_id').html('<%=raw #ruby_variable.to_json%>');
Now it works as expected.
Found out what it is! 😊 (solution for rails 4)
If you have in your ajax call parameters that are not in your permitted list, the record gets saved, you get no error messages about the 'not permitted' parameters, but the update.js.erb won't run - even though your terminal will feed back 'Rendered update.js.erb etc'
If the extra parameter is an attribute in your model, just permit it.
The simplest way to permit non model parameter is to add in your model:
attr_accessor :paramKeyTroublesome
Then you can also permit it in the controller.
in the $ajax call, data needs to be hashed up properly:
data: {model_name: {paramKey1: value, paramKeyTroublesome: value}}
One more problem to be aware of is an error in your update.js file. Nothing will execute if there are any syntax errors. You can check this by going to your browser inspector and enabling Log XMLHttpRequests Then reviewing the output js file.
I'm working with Devise and DeviseInvitable to manage authentication in my app and I'm having some trouble adding AJAX support to InvitationsController#update. The controller in DeviseInvitable looks like this:
# invitations_controller.rb
# PUT /resource/invitation
def update
self.resource = resource_class.accept_invitation!(params[resource_name])
if resource.errors.empty?
set_flash_message :notice, :updated
sign_in(resource_name, resource)
respond_with resource, :location => after_accept_path_for(resource)
else
respond_with_navigational(resource){ render_with_scope :edit }
end
end
This works well when resource.errors.empty? == true and we execute:
respond_with resource, :location => after_accept_path_for(resource)
(i.e. invitations/update.js.erb is rendered and my javascript calls are made). The problem is that when resource.errors.empty? == false, and we execute:
respond_with_navigational(resource){ render_with_scope :edit }
the server says:
Rendered invitations/update.js.erb (1.4ms)
but my javascript calls are not being run. Can anyone explain what respond_with_navigational is supposed to be doing? I've been googling for hours and I haven't found an explanation of this api anywhere.
Thanks!
OK, I figure out what respond_with_navigational is doing. It's defined in the Devise base classes as such:
def respond_with_navigational(*args, &block)
respond_with(*args) do |format|
format.any(*navigational_formats, &block)
end
end
and, navigational_formats is defined in Devise as well:
# Returns real navigational formats which are supported by Rails
def navigational_formats
#navigational_formats ||= Devise.navigational_formats.select{ |format| Mime::EXTENSION_LOOKUP[format.to_s] }
end
So, it's basically a wrapper for respond_with(). In order to get this to work, I had to add the following to my InvitationsController:
respond_to :html, :js
and now, update.js.erb is being rendered properly.