.js.erb file available to all other views? - ruby-on-rails

So, in my rails app I ajaxified the error messages on one of my pages. the process was (so everyone understands) first, in my 'edit' link_to I added :remote => true at the end of it thus having it send an ajax request. I then added the line format.js in my respond_to do |format| block. Then, I made an edit.js.erb file with the following line of code $('#error').html("<%= flash[:error] %>"); which basically finds the error div in the current page and replaces the html in that div with the error flash message. This is cool right? No more annoying page refreshes in the event of an error.
Question is, I want to do this for all my edit and destroy pages, but how without making an edit.js.erb and destroy.js.erb file for each view folder? seems pretty simple, and maybe im just missing an obvious answer because I'm exhausted, but I can't figure it out... so... help?????
EDIT!
this is my edit controller
def edit
user = User.find(session[:id])
#table = Table.find(params[:id])
if user.id != #table.created_by
flash[:error] = "ERROR"
respond_to do |format|
format.js {render :template => 'shared/show_error'}
format.html
end
else
flash[:error] = ""
respond_to do |format|
format.js {render :template => 'table/edit', :formats => :html}
format.html
end
end
end
Problem now is, it works fine for showing the errors but if there are no errors it doesnt action render the edit page... In the server window it shows it did, but it doesnt actually show on the screen... Any ideas?

I would suggest you then make a general JS.erb file, something like:
# app/views/shared/show_errors.js.erb
('#error').html("<%= flash[:error] %>");
And then in your controller action, or from another JS.erb file, just type:
render :template => "shared/show_errors"
And voila!

I actually fixed my own problem by accident... I removed the line {render :template => 'table/edit', :formats => :html} from the else block.

Related

How do I change the render file path for AJAX call

I'm running Rails 2.3.8 and I have a respond_to in my Projects controller create action.
def create
respond_to do |format|
format.html { redirect_to('/') }
format.json :status => 200
end
end
I have an AJAX call to this action. The Rails application then renders
projectdocs/create.erb
My question is, how can I change this file path within my action from create.erb to create.erb.js.
I think your controller-name would be "projectdocs" an not "Project" if he renders "projectdocs/create.erb", but that's not the point.
You can explicit render a js-file using
format.js { render :action => 'create' }
if this Format is requested.
It depends on called format. If client wants js, add format.js and rails will try to render first of all create.js.erb

Rails AJAX - don't redirect or render

Using rails and .js.erb to make an AJAX request (and append values to a div), how do you prevent rendering a new layout? In other words, stay on the same page without going anywhere and just append the fresh data from the server in a div. No reloading the same page, no redirecting.
At the moment my controller looks like this
def update_shipping
#order = Order.find(params[:id])
#order.shipping_option_id = params[:shipping_options]
#order.save!
respond_to do |format|
format.js
format.html
end
end
and my form like zisss:
<%= form_tag update_shipping_order_path(#order), method: :put, remote: true do %>
<%= select_tag 'shipping_options', #options_for_select, onchange: 'this.form.submit()' %>
<% end %>
and my routes look like a so:
resources :orders do
member do
put :update_shipping
end
end
But I get a 'Template is Missing' error
Please help!!
You need to add a update_shipping.js.erb file under app/views/your_controller/ directory. Note the name of the javascript file should be same as the action. Since you have a remote:true in your form so rails will try to render a javascript template in your case update_shipping.js.erb.
Now in your update_shipping.js.erb file write some basic javascript to update the page elements like
#update_shipping.js.erb
$('.some-div').html(<%=j #model.some_value' %>)
Try this:-
respond_to do |format|
format.js { render :nothing => true }
format.html
end
If you don't want to render a layout, you can use !request.xhr? like so:
respond_to do |format|
format.html { layout: !request.xhr? }
format.js
end
If you're looking to get your ajax-powered JS to fire, you just need to call your .js.erb file the same as your view:
#app/views/controller/update_shipping.js.erb
alert("This JS is returned & fired after the Ajax request");
You'll be best doing this in your routes.rb too:
resources :orders do
put :update_shipping
end
A little late, I came across this searching for the same issue. It must of slipped out of my mind at some point while working with action cable, but what is needed is a http response code of no_content. Http response codes tell the browser how to act when a request is returned. Here is a link to a list of them, and their symbols in rails. More on 204 no content
Here is how it would look:
def update_shipping
#order = Order.find(params[:id])
#order.shipping_option_id = params[:shipping_options]
#order.save!
head :no_content #or head 204
end
edit: what solved the solution for me was a link provided by William Denniss in this stack overflow question

How to make :render => nothing work

I have an jquery AJAX call that loads a window. In the window, there is a form with a submit to allow the users to download an item. I have to make this second form use a regular submit so that I can prompt a download.
My problem is when there is no file to download, it redirects to the page in which this file is located.
I am trying many different styles of getting it to render nothing, but none of them seem to work.
unless params[:controller] == "reports"
unless #jobs.present?
flash.now[:error] = "No work orders for this selection."
render :nothing => true
end
end
Also
respond_to do |format|
format.html { render :nothing => true }
end
Nothing seems to work. Any ideas?
Don't use render: nothing. This will "fail" ajax request.
Instead, use:
render json: nil, status: :ok

Rails: rendering the js.erb template using the controller

I have a rails app trying to incorporate some AJAX where clicking new opens a modal window and a form. I want to be able to display the validation errors if it fails so in my create action, i thought about re-rendering the new.js.erb file. Is this the right approach?
def create
#place = Place.new(params[:place])
if #place.save
redirect_to places_path, :notice => "Successfully created place"
else
render "new.js.erb"
end
end
The result I get is escaped js text in my browser like:
$("#new_grouping").html("<div class=\"modal-header\">\n <a class=\"close\" data- dismiss=\"modal\">×<\/a>\n <h3>Create a new menu section<\/h3>\n<\/div>\n<form accept-charset=\"UTF-8\" action=\"/places/1-mama-s-pizza/groupings\" class=\"simple_form new_grouping\" id=\"new_grouping\" method=\"post\" novalidate=\"novalidate\">
I've tried putting various options into the render block but no luck. Any tips?
The best practice would be to support both, AJAX and Non-AJAX calls, in case the user has javascript turned off for any reason.
def create
#place = Place.new(params[:place])
respond_to do |format|
if #place.save
format.html { redirect_to places_path, :notice => "Successfully created place" }
format.js # renders create.js.erb, which could be used to redirect via javascript
else
format.html { render :action => 'new' }
format.js { render :action => 'new' }
end
end
end
The render :action => 'new' actually renders the template of the controller action new which results to new.html.erb respectively to new.js.erb depending if it's a non-AJAX or an AJAX call.
In new.js.erb goes your ERB/javascript code:
$("#new_grouping").html("<%= escape_javascript(...) %>">
As i know, rendering partial in controller is a bad idea, because then response can be without content-type and some browsers can't understand this. if it is some file attached to action you should write
render :action => "create"
or if you need just render a singe partial then in your action file write
<%= render :partial => "path/to/partial" %>
as i said, then you won't have problems with content-type in response

How to redirect after a successful AJAX form submission (Rails 3.2)

Suppose you have an edit form with :remote => true. Your controller method looks like
def update
#article = Article.find(params[:id])
respond_to do |format|
if #article.update_attributes(params[:article])
format.html { redirect_to #article}
format.js { render :js => "window.location.replace('#{article_path(#article)}');"}
else
format.html { render :action => "edit" }
# Render update.js.erb which replaces the body of the form
format.js {}
end
end
end
What's the best way to do the redirect on successful article update in Rails 3.2.1? The raw JS solution seems a little sleazy, but I do like the fact that it's obvious that it's performing the same function as the format.html version.
I would prefer a solution that does not use RJS (if that even works in Rails 3.2?)
How about adding the below line of code on the view file itself
#some_file.js.erb
`window.location = redirect_path
As you mentioned in the question you do not prefer RJS, but I think it's better to follow this pattern better than writing the js code in the controller.
Does your ajax interact with a model (.php,.asp?). My preferred method in this instance is to create a success/fail criteria within the model after submission and redirect directly from there. Not sure if that makes sense in this application though?

Resources