multiple partial in jquery ajax rails 3.2 - ruby-on-rails

How to update multiple partial through ajax in rails 3.2
Here i did my ajax request
$.ajax({
url: "/home/create_entry",
type: "POST",
data: params,
cache: false,
success: function(data) {
$('#'+did).html(data);
// $("#results").html('<%#=j render(:partial => 'explorer', :locals => {:entries => #entries, :entry_count=> #entry_count}) %>');
}
});
In controller written
def create_entry
if request.xhr?
#entry = Entry.new
#entry.title = params[:title]
respond_to do |format|
if #entry.save
flash[:notice] = "Entry created successfully"
#entry = Entry.last
#entries = Entry.where(:user_id => current_user.id).order(sort_column + ' ' + sort_direction)
#entry_count = #entries.count
format.js
end
end
end
And in create_entry.js.erb
<%= render :partial => 'edit_entry_form', :locals => {:entry => #entry}%>
<%= render :partial => 'explorer', :locals => {:entries => #entries}%>
Now i can able to get both data, How can i update both partial after success of ajax request ?
Thanks in advance.

You should look at using jQuery to dynamically insert the contents of these two partials into the areas of the page you want to update. Something like:
$("#divforedit_entry_form").html("<%= escape_javascript(render 'edit_entry_form' :locals => {:entry => #entry})%>");
$("#divforexplorer").html("<%= escape_javascript(render 'explorer' :locals => {:entries => #entries})%>");

First off we need to correct your AJAX call as we don't need to have the server response added onto the page only evaluated (which in Rails happens by default).
Javascript
$.ajax({
url: "/home/create_entry",
type: "POST",
data: params,
cache: false
});
Now we update the controller to perform the logic and get any required data to correctly render the partials.
Controller
def create_entry
if request.xhr?
# Create entry
respond_to do |format|
if #entry.save
# Collect any data needed for view
format.js
end
end
end
end
Now in the view we use jQuery and the Rails javascript helper to replace/insert the partials into the HTML document.
View (create_entry.js.erb)
$("#edit_entry_form").replaceWith("<%= j(render('edit_entry_form', :entry => #entry)) %>");
$("#explorer").replaceWith("<%= j(render('explorer', :entries => #entries)) %>");
The above presumes that the HTML IDs #edit_entry_form and #explorer exist.

Related

Ajax delete for comment is not reloading the partial + rails 3.2

I have got ajax comment submit and delete, submit works perfectly but delete is not working.
Below is my code :-
Controller
def destroy
#status_update = StatusUpdate.find(params[:id])
if #user == current_user
if #status_update.destroy
respond_with do |format|
format.html do
if request.xhr?
render :partial => "users/post_status_update", :locals => {:user => #user}, :layout => false, :status => :created
else
redirect_to #user
end
end
end
end
end
end
Javascript
$(document).ready(function(){
$('.delete-status-update')
.on("ajax:beforeSend", function(evt, xhr, settings){
})
.on("ajax:success", function(evt, data, status, xhr){
$('.status-partial').replaceWith(xhr.responseText);
})
});
View
.status-partial
-#user.status_updates.latest.limit(5).each do |status_update|
.row-fluid.cycle-status-update{:class => cycle("dark", "light")}
.row-fluid
.span11
= status_update.status
.span1
.delete-status-update-link
%strong= link_to "X", [#user,status_update], :remote => true, :method => :delete, :class => "delete-status-update"
.row-fluid
.time-ago-in-words
="#{time_ago_in_words(status_update.created_at)} ago"
Problem is status partial is not getting replaced once I click on the delete link, after refreshing the page ajax delete works for the first time then it again stops to work.
You are needlessly complicating everything. Your destroy controller could be simple as follows:
def destroy
#status_update = StatusUpdate.find(params[:id])
if #user == current_user
unless #status_update.destroy
redirect_to #user
end
end
end
In your views, instead of calling through $.ajax, try a rails link_to "action", action_path, remote: true
Name your html view file as destroy.js.erb.
These can be its contents:
$('.status-partial').html(<%= #user.generate_new_content.to_s %>);
Rails will take care of the rest. When you click on the link, the element with class 'status-partial' will have its html content replaced with "some new content".
It's a good practice to separate your HTML and AJAX responses, and Rails provides a convenient way to do it. Use it.
I think it would be better if you would do
respond_with do |format|
format.js
and then have a file called destroy.js.erb to place the javascript that should fire after a deletion
The issue was with syntax of .on used in javascript file, it does not work like .live. Changing the syntax to
$(document).ready(function(){
$(document).on("ajax:success", "#create_status_update_form", function(evt, data, status, xhr){
$('.status-partial').replaceWith(xhr.responseText);
$('.comment-text').val('');
})
});
solved the problem.

ruby on rails render partial inside a json array

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.

rails ajax pagination with partials

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

Rails 3: "redirect_to" doesn't work well after Ajax call

In my Rails 3 application user adds a new message to forum using Ajax:
<%= form_tag("/forum/add_new_message", :remote => true) do %>
<%= text_area_tag("new_message_area") %>
<% end %>
Here is my controller's code:
def index
#messages = Message.all
end
def add_new_message
Message.create(:text => params[:new_message_area], ...)
redirect_to(:action => 'index')
end
The problem is that after user adds a new message, redirect_to(:action => 'index') executed, but the page is not refreshed, i.e. I don't see the new message.
Why ?
The web browser is expecting some javascript to be executed after the ajax has been called. Your code should work when javascript is disabled in the browser.
In the add_new_message method you should add:
respond_to do |format|
format.html { redirect_to(:action => 'index') }
format.js
end
Then some javascript in add_new_message.js.erb will be executed, so to redirect to the index, the code in add_new_message.js.erb should look like:
window.location = '<%= forums_path %>'; //or whatever other path
Although both the HTML and javascript do the same thing. Why is the ajax needed in the first place?
I'd be tempted to go for something like this in the controller:
def index
#messages = Message.all
end
def add_new_message
Message.create(:text => params[:new_message_area], ...)
render js: %(window.location.pathname='#{messages_path}')
end

Is there an AJAX function that can just GET a rails partial?

My controller is shared by links from a search result page that needs a layout, and from the profile page itself that does not need a layout. What I would like to accomplish is a single controller method show that is both capable of drawing the partial by AJAX from the profile page, and draw the partial and layout from the search results.
The most important restriction I have is that I can not set the dataType: to script . It has to be html . So I can't use that spiffy AJAX script call that renders the JS without the controller's format.html getting involved.
tabs_controller.js
def show
#organization = Organization.find(params[:organization_id])
#tab = #organization.tabs.find(params[:id])
respond_to do |format|
format.html { render :partial => 'tab', :layout => 'myHQpage' }
format.js
end
end
javascript
$.get($(this).attr('href'), null, null, "html");
show.html.haml
= render :partial => 'tab'
What AJAX function can I use here that just draws the partial, and not the entire layout?
I'm not sure to really understand but this may help you.
Yo can add a :layout => false to the format.js block.
def show
#organization = Organization.find(params[:organization_id])
#tab = #organization.tabs.find(params[:id])
respond_to do |format|
format.html { render :partial => 'tab', :layout => 'myHQpage' }
format.js { render :partial => 'tab', :layout => false }
end
end
Keep the 'script' dataType setting and just add a wrappertag around your search results. Then use the jQuery replaceWith function to replace the content of that tag:
_tag.html.erb:
<div id="search">
...
</div>
show.js.erb:
$('#search').replaceWith('<%= escape_javascript(render "tab") %>');

Resources