Everything I am reading about rails 3 and AJAX says that we should have
respond_to do |format|
#wines = Wine.all(:conditions => {:category => "Sparkling"})
format.js
end
and then a seperate js.erb file that is
$("wines").update("<%= escape_javascript(render :partial => "sparkling")%>")
but that one line js file seems a little extreme, can I do something like this:
respond_to do |format|
#wines = Wine.all(:conditions => {:category => "Sparkling"})
format.js {render :js => '$("wines").update("<%= escape_javascript(render :partial => "sparkling")%>"')}
end
and then leave out the extra .js.erb file
The problem I see here is a double render (am noob so I'm not sure)? What is the best way to do this?
Inline RJS is a bad practice, but you can use it like this:
def your_action
#wines = Wine.all(:conditions => {:category => "Sparkling"})
respond_to do |format|
format.js {render :update do |page|
page << '$("wines").update("<%= escape_javascript(render :partial => "sparkling")%>"')
end}
end
end
UPD
No, it's not silly to store one more file. It makes your controllers cleaner. Look with your_action.js.erb
# your controller
def your_action
#wines = Wine.all(:conditions => {:category => "Sparkling"})
end
# your you_action.js.erb
$("wines").update("<%= escape_javascript(render :partial => "sparkling")%>"
That is two lines instead of 6 :)
Related
I am trying to render a partial for the ajax request but i can't find how to do it using Ruby on Rails...
here what my array variable
#return = { :error => false, :response => "Added", :partial => ... }
render :json => ActiveSupport::JSON.encode( #return )
where ... is where the partial(html) should be...
the method name is add_item, its controller is items and i have created an add_item.html.erb file inside the items folder which has the HTML i want to pass to the array and use jQuery to add it to the DOM
i guess this could be done using
render :partial => "partial", :object => #object
but how can i add this into the array above?
Solution:
#return = { :error => false, :response => "Added", :partial => render_to_string(:partial => "partial/path", :object => #object) }
The way I do what I think you're trying to do is to fire an ajax message at add_item, and then in add_item have:
def add_item
respond_to do |format|
format.js
end
end
and make an add_item.js.erb with the jQuery contents:
$('#div-for-code').html('<%= escape_javascript(render :partial => "mypartial") %>');
not sure that it's the best way but it's worked for me.
I am using the will paginate gem for pagination. Things wok fine for me.I am trying to ajaxify it and I followed the http://railscasts.com/episodes/240-search-sort-paginate-with-ajax tutorial. But Ajax request is not being fired for me.
I have a index view. The view renders a partial called "_browser_form" which in turn renders a partial called "_listing". So I wanted to paginate the table in the _listing.
Please let me know if there is any error in my approach.
My controller:
def index
#ics = Ic.search(params[:root_name],params[:suite_name],params[:case_name],params[:name],'f').paginate(:per_page =>5, :page => params[:all_ics])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #ics }
end
end
My _browser_form.html.haml which is rendered from index.html.haml
- form_tag "/ics/mass_action", :method => :post, :multipart => true do
<div id="update_ics_table">
= render "listing", :show_check_boxes => show_check_boxes, :root_name=>params[:root_name],:suite_name=>params[:suite_name],:case_name=>params[:case_name],:name=>params[:name],:ic_filter=>1
</div>
=will_paginate #ics,:param_name=>:all_ics
My index.js.erb file:
$('#update_ics_table').html("<%= escape_javascript(render :partial => 'listing' ,:object => #ics) %>")
My .js file:
$(function () {
$('#update_ics_table .pagination a').live('click',
function () {
$.getScript(this.href);
return false;
}
);
});
Thanks,
Ramya.
Remove what you're doing in the Javascript and do this in the controller:
format.js {
render :update do |page|
page.replace 'listing', :partial => 'listing'
end
}
Similar: Best way to get will_paginate working with Ajax
It might have something to do with the fact that you're using HAML views and an js.erb file, but I don't use HAML so I can't be certain. Have a look at nex3's answer at this SO: How to send back js.haml in rails
If that is not the case, I think you need to change your respond_to controller action block to this:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #ics }
format.js #<------ This will execute index.js.erb
end
I have a subscriber#create method that is only used for ajax submits to it (the html form uses data-remote="true" to do the Ajax. The form does indeed submit and the data ends up in the db but the method throws an error saying that the template was not found.
How can I specify a function as being an Ajax handler in Rails? -- one that doesn't have to render a template, etc.
Here is what the method looks like:
class SubscribersController < ApplicationController
def create
Subscriber.create(:email => params[:email],
:ip_address => request.remote_ip,
:referring_page => request.referer ) unless Subscriber.find_by_email(params[:email])
end
end
You should handle the call in your respond_to properly.
...
respond_to do |format|
format.html
format.js { :nothing => true }
end
The thing it, you should probably return something. Even if it is an AJAX call, you should send something back to let the caller know that the creation was a success.
def create
#subscriber = Subscriber.new(#your params)
respond_to do |format|
if #subscriber.save
format.js { render :json => #subscriber, :status => :created, :location => #susbscriber }
else
format.js { render :json => #susbcriber.errors, :status => :unprocessable_entity }
end
end
end
Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.
you want something like render :layout => !request.xhr? in your controller, this will prevent the layout if the request is ajax
I recently changed the pagination with will_paginate in my Rails (2.3.4) app to use Ajax for the pagination and records per page. The pagination was done using the method described here: http://github.com/mislav/will_paginate/wiki/Ajax-pagination
I'm using this code in my view:
Records per page: <%= select_tag :per_page, options_for_select([4,8,24,100,500], #per_page.to_i), :onchange => remote_function(:url => users_path, :method => :get, :with => "'per_page=' + this.getValue()") %>
This works fine if I'm not viewing search results. But if I do a search and them attempt to change the records-per-page, my search results are lost and all records are returned. I'm pretty sure this is due to the url I'm calling in my remote_function, but I don't know how to fix it.
This is the code in my controller:
def index
#search = User.search(params[:search])
#search.order||="ascend_by_last_name"
if #search.count > 0
#users = #search.paginate(:page => params[:page], :per_page => users_per_page )
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
format.csv { send_data #users.to_csv }
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace 'results', :partial => 'userview'
end
}
end
else
flash[:notice] = "Sorry, your search didn't return any results."
redirect_to users_path
end
end
Any help would be appreciated! Thanks.
You can append the per_page param to the end of the current query string.
:with => "'#{request.query_string}&per_page=' + this.getValue()"
This assumes there is a current query string, which could cause issue.
I have an action in my PostsController named 'tagged', which I want to return all posts tagged with whatever term.
In my routes.rb I have the following (at the top):
map.connect 'posts/tagged/:tag', { :controller => 'posts', :action => 'tagged', :tag => /[a-z\-]+/ }
Yet navigating to posts/tagged/yes returns a RecordNotFound error:
Couldn't find Post without an ID
In my tagged.html.erb file, I'll eventually be using the find_tagged_with method from acts_as_taggable_on_steroids, but for now I've put a simple Post.find(:all) to eliminate the possibility of error.
It seems like my map.connect is being overridden, and the same error occurs even if I comment the whole of the routes.rb file out except my new line.
Ok, because you can comment out the default routes that means your problem is not in your routes at all. It's that your tagged action in the posts controller probably has something like this.
def tagged
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
Or perhaps if you spent a little more time it looks like this:
def tagged
#post = Post.find(params[:tagged])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
Where as what you want is this:
def tagged
#post = Post.find(:all, :conditions => {:tagged => params[:tagged]})
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
Anyway, you should be writing functional tests for this stuff and not testing in the browser.
Why not add a RESTful route for the "tagged" action?
map.resources :posts, :member => { :tagged => :put }