I'm using Rails version 3.0.9 and jquery.
The problem is that when you click on the link, the div is not updated.
There are two actions: "show" and "time". Initial position - show.
Controller code was (ajax_controller.rb):
class AjaxController < ApplicationController
respond_to :html, :js
def show
end
def time
end
end
By clicking on the link in the div should be loaded time.
Next code (show.html.erb):
<h1>Ajax show</h1>
Click this link to show the current
<%= link_to "time", :url=>{:action => "time"}, :remote => true%>.<br/>
<div id='time_div'>
</div>
Also, there are files time.html.erb and time.js.erb.
Follow code (time.js.erb):
$('#time_div').html('<%= escape_javascript(render :text => "The current time is #{Time.now.to_s}") %>');
But nothing happens. jquery connected.
In what may be the problem?
You can have issues with routes. Do you have something like this in your routes.rb?
RAILS_ROOT/config/routes.rb
get '/time', :to => 'ajax_controller#time', :as => :ajax_time
and then you should call the url with rails helper like this
<%= link_to "time", ajax_time_path, :remote => true %>
You can look at your log to see if time.js.erb is indeed rendered. It is possible that the HTML version is rendered instead. If that's the case, remove the HTML version.
Related
I am trying to dynamically populate a select list and I am getting a 404 error when I make my ajax call to my controller. I have looked around but cannot find out why I am getting this error.
My controller where the method I want to call is.
class UsersController < ApplicationController
def index
##users = User.all
myList = [["A",1],["B"],2]
#classList = myList
render "index.html.erb"
end
.
.
.
def changeclasses
#classlist = [["B",2]]
end
end
And this is my view
<%= form_for UnoClass.new do |f| %>
Department: <%= select_tag(:city_id, options_for_select([['Accounting', 'ACCT'], 2),
{ id: 'departSelect'}) %>
<br />
Course : <%= select_tag(:course, options_for_select(#classList)) %>
<br />
Section : <%= f.text_area :section %>
<br />
<%= f.text_area :sessionId, value: request.session_options[:id], style: "display:none;" %>
<%= f.submit %>
<% end %>
<script>
$(document).ready(function() {
$('#departSelect').change(function() {
$.ajax({
url : "/changeclasses"
});
});
});
</script>
and my routes.rb
Rails.application.routes.draw do
resources :uno_classes
resources :users
root :to => 'users#index'
get '/changeclasses' => "users#changeclasses"
This is the error that I grab from the developer tools on chrome.
GET http://localhost:3000/changeclasses 404 (Not Found)
So, when I make a change to the upper select box departSelect, it makes a call to changeclasses but it cannot find it.
Also when I do rake routes the correct route shows up.
changeclasses GET /changeclasses(.:format) users#changeclasses
I have not implemented the method yet but it should change the #classList and therefore change the contents of the course select box and it never gets called because of the 404 error.
Any help would be appreciated because I cannot figure out why there is a problem here.
Here's some ideas on things you can try to get it working.
First. Create a view called "changeclasses.js.erb" in your Users views folder which is what Rails will by default look to load unless you tell it otherwise since its a js request. You can/should also put the js that you want to run with this particular method in that file (changeclasses.js.erb).
Second. Try updating the ajax call's datatype to "script" so that it will be processed by your controller as js.
$.ajax({
url : "/changeclasses",
dataType: "script"
});
Third. If all that doesn't fix it, I would add the below code to your controller to make it sure it is responding to js requests.
class UsersController < ApplicationController
respond_to :js
Hope one of those helps!
I am trying to setup a navigation bar on my home page that loads a partial into a div element when the user clicks on the links. I have followed the steps in this post and modified them as I thought I needed:
Rails 3 - link_to to call partial using jquery ajax
My code:
views/pages/home.html.erb:
<%= link_to "Files", :action => 'load_upload_partial', :remote => true %>
.
.
.
<div id="main_frame"></div>
pages_controller:
def load_upload_partial
respond_to do | format |
format.js {render :layout => false}
end
end
/views/uploads/load_upload_partial.js.erb:
$("#main_frame").html( "<%= escape_javascript( render( :partial => "/upload/upload_form" ) %>" );
The partial in this example is just a form. When I click on the link I get a blank page with this is the address bar:
http://localhost:3000/load_upload_partial?remote=true
This makes me think that link is not triggering an ajax GET request (if that's the correct terminology). If that is the case is there anything I need to be adding to my application.js file? I followed the railscast #136 on rails and jquery but couldn't figure out which bits of the application.js code applied to my case.
Any thoughts are much appreciated. Thanks. Tom
I now tend to avoid using RJS like you're intending to. I prefer creating js templates with tools like handlebars.
I only use ajax to get raw data and then recreate the partial client side. It's much better for server load and data transfer.
I think you have to change your link_to to:
<%= link_to "Files", {:action => 'load_upload_partial' }, remote => true %>
The problem is related to the method signature of link_to.
ran into this same problem - the hint was in the malformed html produced - take a look at the value of the href attribute of the tag produced by your code. I bet it looks funky. Here's the correct code:
<%= link_to "Files", your_path, action: 'load_upload_partial', remote: true %>
have you tried using .load() instead of .html()?
Also, try using this line instead:
$("#main_frame").html( "<%= escape_javascript( render( :partial => '/upload/upload_form' ) %>" );
I am using Ruby on Rails 3 with Prototype/Scriptaculous and I am trying to update a 'div' content after that ActiveRecord values are changed, without reload the page.
In the "edit.html.erb" I have:
...
<div id="test_id">
<%= #account.name.to_s %>
</div>
<%= link_to_function( "Make test" ) do |page|
page.replace_html :test_id, #account.name.to_s
end %>
...
Before clicking on "Make test" I update the '#account.name' value, even via AJAX. Then, clicking on "Make test", the template doesn't changes.
These are steps:
I show the page
I update '#account.name' via AJAX
I click on "Make test"
'div' with 'id="test_id"' doesn't change!
What am I doing wrong?
P.S.: I think that #account is not reloaded in the page, also if his values are changed in the database. If so, what should I do?
I have seen the Railscasts "AJAX with RJS" and I followed an example in that (it is like the my), but it doesn't work for me.
If you have rendered edit.html.erb when the value of #account.name is "George", the HTML will remain the same (with the value "George") until you refresh it. Your call to link_to_function is, on page load, rendering an html link that calls javascript that replaces the inner html of the "test_id" div with 'George'. Unless you replace that HTML, it will always replace the inner html of that div with 'George'.
It's hard to recommend a solution without knowing exactly what you'd like to do...
updated to have more detail:
If you are making an AJAX call that changes the value of the account name on the server to "Fred", and want that change to appear on the page, you should refresh the parts of the page that use that value in that same AJAX call (that same controller action).
Your link_to_function generates HTML like this (if #account.name was 'George' when the page was rendered):
<a onclick="try { Element.update("test_id", "George"); ... >Make test</a>
It is not an ajax call, it is just a link that executes javascript. If you want to make it an ajax call that finds the latest value of the account name and refreshes the test_id div, do something like this:
<%# you need prototype included, but it should probably be in application.rhtml %>
<%= javascript_include_tag "prototype.js" %>
<div id="test_id">
<%= #account.name.to_s %>
</div>
<%= link_to_remote "Make test", :url => { :controller => "account", :action => "change_name" } %>
The 'Make test' link will now perform an AJAX call to the 'change_name' method in the 'account' controller. This method would look something like this:
def change_name
# here you would load the account from the db; I'm cheating
#account = Account.new(:name => "Fred")
render :update do |page|
page.replace_html :test_id, :text => #account.name.to_s
end
end
I am attempting to reload a partial on a page periodically but it does not seem to be working. The partial loads correctly when I first load the page but it will not update when I introduce new info to it without reloadig the page. The view looks like:
<div id="menuarea"style="height: 399px; width: 181px">
<%=periodically_call_remote(:url => {:action => :findnew}, :frequency => '20', :update => 'menuarea') %>
<p> Please select a color </p>
<%#partil renders the color table %>
<%= render :partial => "colortable" %>
</div>
and the controller looks like:
def findnew
#bunny= Xparsing::Xmlparse.new
#fuzzybunny= #bunny.hex1
#pinkbunny=#bunny.pantone1
#blackbunny=#bunny.description1
render(:partial => 'colortable')
end
All I am attemptinging to do is reload the partial colortable without reloading the page. I am seeing the render color table in the comand line every 20 seconds but the table is not reloading on the page What do I need to fix?
Are you sure you are not overwriting the Javascript containing periodically_call_remote when you update the <div>?
Don't you want to put that script outside the updating <div>? Or put it into the partial and remove it from where you have it now.
turns out it was an issue with jquery and prototype. I removed jquery and it worked perfectly. Still trying to figure out why
I am running into a strange problem.
I simply want to display a loading icon on the page when pressing a button.
If my call to form_remote_for contains Ajax options then the RJS script does not work.
This works ("loading" is hidden by the controller and RJS):
View:
<%=form_remote_for(:job, #job, {:url => {:action=>:create}}) do |f| %>
[...]
<div id="loading">Loading...</div>
controller:
def create
render :action => "create.js.rjs"
end
RJS:
page.hide 'loading'
This does not work (just adding :loading=> and loading is shown by the view but not hidden back by the controller as it was before):
<%=form_remote_for(:job, #job, {:url => {:action=>:create}}, {:loading=>"$('loading').show()"}) do |f| %>
[...]
<div id="loading" style="display:none;">Loading...</div>
So if my call to form_remote_for contains Ajax options then the RJS script does not work. Why?
Change your form to:
<% form_remote_for (:job, #job, :url => {:action => :create}, :loading =>"$('loading').show()") do |f| %>
# ...
<% end %>
Make sure create is:
# POST /jobs
# POST /jobs.xml
def create
render :action => "create.js.rjs"
end
And make sure your create.js.rjs is:
page.hide 'loading'
This scenario works for me. As you had it, it was returning the erb in the template because it was posting to "new" -- based on a quick scaffold implementation I did. Now I might still be missing something because as I said before the massive edit, I'm new, but this should get you going.
EDIT: Removed "is this your code?" post.
While not directly answering your question of "why" it isn't working, have you looked at using the :loaded parameter to hide the loading DIV rather than rely on the rjs file?
Assuming your using prototype you should use the Ajax.Responders to do the show/hide:
Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
if($('loading') && Ajax.activeRequestCount>0) {
Effect.Appear('loading',{duration:0.4,queue:'end'});
};
},
onComplete: function() {
Ajax.activeRequestCount--;
if($('loading') && Ajax.activeRequestCount==0) {
Effect.Fade('loading',{duration:0.4,queue:'end'});
};
}
});
You can stick it in public/javascripts/application.js
Unobtrusive javascript - will work on any page with a hidden loading div and ajax events.