Ruby ajax call initiates unwated Popup Box - javascript

I have an AJAX call for one of my routes in my Ruby on Rails project. It calls a method in a Ruby Controller to update flags on several of my objects, and then I need the page to reload to reflect those changes. This was my solution, at the end of the Ruby method:
respond_to do |format|
format.js {render js: "window.location = '#{processed_items_path(params)}'" }
end
This does exactly what I need it to do, it refreshes the page and pulls the user back to the top to see a flash notice. However, before doing so, it pops up a window that says:
The page at localhost says:
"window.location = '#{processed_items_path(params)}'"
And it requires you to click "OK" before you can continue on. Is there any way to get rid of that box?

According to the comments above, instead of redirecting it'll be better to just render your partial containing your table
I'm assuming your ajax call is working (as it's taking you to your method). For rendering your partial you can do:
def your_method
#your logic of updating attributes
respond_to do |format|
format.js {} # this will let rails look for a file named your_method.js.erb in your view
end
end
Now you simply need to render your partial in your_method.js.erb
$("#some_id_of_parent_element").html("<%=j render partial: "partial_containing_table", locals: { :your_local => partial_local} %>");
For details refer to Working with javascript in rails

Related

The right way to do remote (ajax) calls in Ruby on Rails

I'm making a Single Page Application with Ruby on Rails (it's my first ruby project ever so I'm definitely missing a lot of stuff yet).
So I have a side menu with some links and the right part of the page is supposed to hold a container which is meant to be filled with some content of partial pages.
The typical menu link I have now looks this way:
<%= link_to t('my-groups'), :controller => 'dashboard', :action => 'mygroups', :remote => true %>
I have a dashboard controller, here's the simplified version of it
class DashboardController < ApplicationController
def mygroups
respond_to do |format|
format.js
end
end
I have a dashboard template with the container div in it
<div class="right_col" role="main">
<h2>This is the default content of center page</h2>
</div>
And here's the routes.rb path for it:
get 'dashboard/mygroups' => 'dashboard#mygroups'
I also have one partial page alogside with my dashboard template and it's called _mygroups.html.erb and a javascript file mygroups.js.erb which is called as my controller action
look at the screenshot of the structure
The contents of this js.erb file are:
$('.right_col').html("<%= escape_javascript(render(:partial => 'mygroups')) %>");
It all works and the partial contents appear inside the container on link click just fine.
But there are still 2 problems I couldn't google the answer for
The questions part:
1) It works with Ajax call but if I simply put this http://localhost:3000/dashboard/mygroups to my browser's navigation line and hit enter, it will give me this error
ActionController::UnknownFormat in DashboardController#mygroups
ActionController::UnknownFormat
Extracted source (around line #70):
def mygroups
respond_to do |format|
format.js end end
How can I avoid this and just redirect to index in this case?
I understand that ajax uses POST, but I tried to use post instead of get in routes.rb for this action, and it didn't work at all
2) What if I have a lot of actions for different partial pages, do I have to create a new js.erb file for each action? Can't it be done in some simplier way with just one file?
3) Is it possible to not specify controller and action on this link explicitly?
<%= link_to t('my-groups'), :controller => 'dashboard', :action => 'mygroups', :remote => true %>
I mean since it's supposed to be a POST ajax request, how come I need to display the url like this http://localhost:3000/dashboard/mygroups to a user?
Add format.html in controller like:
class DashboardController < ApplicationController
def mygroups
if request.xhr?
respond_to do |format|
format.js
end
else
redirect_to root_url
end
end
you can add url in link_to tag like:
<%= link_to t('my-groups'), '/dashboard/mygroups', :remote => true %>
Answers to you questions
When you hit the URL in browser, it sends vanilla HTTP get request(non-ajax) which your controller action is not configured to handle it. You need to add format.html and template named groups.html.erb where generally you will list all the groups, I guess.
respond_to do |format|
format.html
format.js
end
Ideally you have to create separate file for each action but if you can take something common out of different action then you can move common template code to a partial and render it either in a separate template having something special or from the controller action directly.
Yes. The rails way is to use routes helper. Run rake routes to list all available routes in your app and find relevant helpers.
I would strongly suggest to read the rails guide to understand how everything works.

Ruby on Rails -> Create div dynamically

I work on a task manager app, and I want to create html div 'cards' (with title, duration etc...), with all the datas I got on a database in rails.
I guess that I have to use javascript functions, but I can't get a way to do it.
I saw a lot of things on google, but I can't find exactly javascript calls from a rails controller (because I only catch all datas in the controller).
Here is my controller :
def new
# Retrieve all tasks in the project
#taskModel = Task.new()
#projectTasks = #taskModel.getProjectTasks()
# Add tasks on html
(0..#projectTasks.length).each do |i|
respond_to do |format|
format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
end
end
end
and my js file :
window.createTask = (title, content, duration) ->
card = document.createElement('div');
document.getElementsByClassName('content')[0].appendChild(card);
With my code, I get this error : ActionController::UnknownFormat
ActionController::UnknownFormat indicated that your ajax request is interpreted as a request with the wrong format. To answer this part better you'd have to post the javascript with the ajax call.
Secondly, you have to rethink the render in this block
(0..#projectTasks.length).each do |i|
respond_to do |format|
format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
end
end
You are calling respond_to multiple times which is just wrong. Put this loop into a new.js.erb view.

How to improve speed execution of coffeescript in rails?

To increase speed of page loading I`ve implemented creation comments via AJAX. It is simple and not heavyweight.In controller action I have:
def create
#comment = #commentable.comments.new(params_comment)
respond_to do |format|
if #comment.save
flash.now[:notice] = "Your comment added."
#response = {comment: #comment, model: #commentable}
format.js { #response }
format.html { redirect_to #commentable }
else
format.js { render nothing: :true, status: :not_acceptable }
format.html { redirect_to #commentable, status: :not_acceptable }
end
end
end
and js file:
$("<%= escape_javascript( render 'comments/comment', #response)%>").appendTo(".comments").hide().fadeIn(500)
$('.notice-wrapper').html("<%= j(render partial: 'shared/notice') %>")
$('.alert').fadeOut(3000)
if $(".no-comments").css("display") is 'block'
$(".no-comments").hide()
$(".new_answer").hide()
$(".open").show()
But instead of speed up performance I got the opposite effect. Response time through JavaScript increased on 100-200 ms(~300ms total). Is this normal behavior or I am doing something wrong? Is there any way to improve speed little bit?
My performance test:
UPD:
My performance test with just JS file.
Let's put aside for the moment my opinion that embedding ERB in CoffeeScript is utterly gross to look at and unmaintainable. It is indisputable that there's a huge performance impact when you generate and compile CoffeeScript on every request.
You also lose any chance at HTTP caching.
My first suggestion would be to separate CoffeeScript from ERB. Populate hidden fields in your ERB with the data you need, and then mine those fields in your CoffeeScript.
But if you must embed ERB in what should be static files, embed the ERB tags in pure JavaScript instead, and let the compiled CoffeeScript use those.
The code you've written wouldn't really be expected to speed up the request, because Rails still need to process all the ERB etc. You're still returning rendered HTML and sending it to the browser where it is added to the DOM.
If you wanted to make it 'faster' you could simply render the #response as json and deal with it on the client using jQuery or a front end framework.
The code does make it nicer for the user, however, because it doesn't refresh the entire page.
My suggestion would be to hook into the form request, and on success, render the new comment, else re-render form with errors. An example:
# app/javascripts/comments.coffee
$('#comment-form').bind 'ajax:complete', (data, status, xhr) ->
// psuedo code
1. if status is success
append comment -- $('#comments').append(data.comment)
2. else
re-render form with errors -- $('#comment-form').html(data.form)
Return comment template (comments/comment) and append to comments
Update your controller to return the form with JS response if not_acceptable.
Note the file is found in app/javascripts/comments.coffee

Rails render JS partial printing code to page

I'm using AJAX in my Rails app to render a JS error message when needed. It was working initially, but now coming back to it some time later, it still shows the JS error message but for some reason it now also prints the entire JS file as HTML in the window. This is what's called in the controller:
respond_to do |format|
format.js { render :partial => 'error' }
end
My file named _error.js.erb contains some JS which isn't relevant as regardless of what it contains Rails prints it to the window still.
This is what the JS looks like outputted to the window: (I tried commenting out the JS to see if it made a difference)
You can try it with some modification :
respond_to do |format|
format.js
end
Inside the action and in the view action_name.js.erb write your js code ar if you want to put your erb then use escape_javascript.
Check the following link :
Why escape_javascript before rendering a partial?
I did it! In case there will be someone else wondering a few years later, there's the answer: you should put rendered value in a javascript_tag inside your html.erb. Like this:
javascript_tag render: 'error'
that will put what rendered between <script>...</script> tags and escape all unnecessary code.
Here's the documentation on it

Rails 3.1 Ajax question

I have a scaffold called post which has a title and a description. On my layout I have a link to create a new post that has :remote => true. How would I make it when I click on that remote link to change the content of a div so that I can create a new post?
Let's suppose the action you will use is called new.
You should create a file called new.js.erb into views/posts that will be rendered when you post remotely your form. That file must include the javascript that places the new post into the div you want to fill. As an example, it could contain
# new.js.erb
$('div#container').html("<p><%= escape_javascript(#post.title) %></p>").append("<p><%= escape_javascript(#post.content) %></p>");
The javascript will be executed immediately after the ajax post is finished and the new post is created. Remember the following:
- You have to include jQuery
- You have to specify in posts_controller the ability to render .js format, something like
# posts_controller.erb
def create
#post = Post.new(params[:post])
respond_to do |format|
if #post.save
format.html { redirect_to(#post, :notice => 'Post created via non AJAX.') }
format.js # the actual ajax call
else
format.html { render :action => "new" }
end
end
end

Categories

Resources