How can I hide a search button and show a spinner while my AJAX partial loads in rails 3.1? - ajax

I have a partial which returns results from the Amazon-ecs API (searches for books). It takes about 2.5 seconds to return values, so I want to add a spinner (and ideally hide the search button) but I've had a tough time getting it to work.
I already have javascript refreshing the partial with the results. I'd just like the button to give me a spinner (and hide the search button) until the partial finishes reloading.
Here is my main view (index.html.erb) which renders a partial of search results, each of which is added temporarily as an object in AmazonItems:
<%= form_tag amazon_items_path, :method => :get, :remote => true do %>
<p>
<%= text_field_tag :query, params[:query] %>
<span id="spinner" style="display:none">
<%= image_tag 'ajax-loader.gif' %>
</span>
<span id="search_button">
<%= submit_tag "Search" %>
</span>
</p>
<% end %>
<h1>Searching Amazon</h1>
<div id="amazon_returned">
<%= render 'amazon_returned' %>
</div>
My only JS code is in the update.js.erb file, which looks like:
$("#amazon_returned").html("<%=j render 'amazon_returned' %>");
I'm sure this is easy, but I can't get it work. Thanks!
EDIT: my partial "_amazon_returned.html.erb" looks like
<table>
<% for amazon_item in #amazon_items %>
<td> amazon_item.title </td>
...ETC...
<% end %>
</table>

You can hook into the before event to do this:
$(function() {
$("form").on("ajax:before", function() {
$("#spinner, #search_button").toggle();
});
});
Then, in your update.js.erb, add this again to toggle them back:
$("#spinner, #search_button").toggle();

Went with Dylan's answer, added the toggle to the update.js.erb and inserted the following into the view:
<script>
$(function() {
$("#search_button").click(function() {
$("#spinner, #search_button").toggle();
});
});
</script>
Very cool! Thanks again for the help.

Related

Else part is not working in Rails ajax form

I have a Rails ajax form to submit.When user will give the correct data it will search the database and do the operation accordingly.If user is giving the Wrong data it should display user to alert message.But it is not happening like that.
I am explaining my codes below.
home.html.erb
<% if current_admin %>
<p class="flash-message"><%=flash[:notice]%></p>
<div class="col-md-6" style="float:none; margin:auto;">
<%= form_for :sdf ,:url => {:action => "scan_report" },remote: true do |f| %>
<% if params[:receipt_no] %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control", :value => params[:receipt_no] %><%= f.submit "Scan Report" %>
</div>
<% else %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control",placeholder:"Receipt No. scan" %><%= f.submit "Scan Report" %>
</div>
<% end %>
<% end %>
<% end %>
controller/homes_contorller.rb
class HomesController < ApplicationController
def home
#sdf=TSdf.new
respond_to do |format|
format.html
format.js
end
end
def scan_report
if #sdf=TSdf.find_by_Receipt_No(params[:sdf][:Receipt_No])
if #sdf && #sdf.HCSY_Status=='YES'
#hcsy=THcsy.find_by_Sdp_Id(#sdf.Sdp_Id)
#hcsy_deatils=THcsyDetails.find_by_HCSY_ID(#hcsy.id)
#woods=THcsyFundTypeMaster.find_by_Fund_Type_Code(1)
#burn=THcsyFundTypeMaster.find_by_Fund_Type_Code(2)
#good=THcsyFundTypeMaster.find_by_Fund_Type_Code(3)
#swd=THcsyFundTypeMaster.find_by_Fund_Type_Code(5)
#photo=THcsyFundTypeMaster.find_by_Fund_Type_Code(6)
end
else
flash[:notice]="Not Found"
end
end
end
In this form its only taking the correct input but if user is trying to give the wrong input the else part is not executing.Please help me to resolve this error and let me to know how can i make this ajax call in below format.
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
Please help me.I am using Rails version 3.2.19.
Here you send AJAX POST request to scan_report, and if it is successful it should render template scan_report.js.erb, and rendered template will appear in json variable in success callback.
But if params are not valid, the same template is rendered, but all instance variables are missing. And probably empty json is returned or an error appears in log.
Anyway, if you'd like to change flash in remote form, you should put custom code in fail callback. Something like
$("#flash").html('<%= j render flash[:notice] %>');

Understanding Ajax in Rails 3

I thought I understood Ajax in Rails 3 to a point but think I am confusing myself somewhere or misinterpreted something. My understanding is that if I want to call different content on the same page then i create a js.erb file for that particular action. For example if i have an action of tynewyddnews, I will have an tynewyddnews view and a tynewyddnews.js.erb file.
I then create a partial to render on that page and call that partial in my .js.erb file.
Example
View
<% #tynewyddpost.each do |t| %>
<li>
<% single = t.photos.first %>
<a class="photo" href="#"><%= image_tag(single.avatar.url(:thumbnail_news_images)) %></a>
<p><%= link_to t.title, tynewyddnews_path(:type => 'tynewyddnews'), :post_id => t.id, :remote => true %></p>
<p class="date"><%= date_output(t.published_on) %></p>
</li>
<% end %>
<div class="post-item">
<h2><%= #tynewyddpostlatest.title %></h2>
<div id="work-samples">
<% for photo in #tynewyddpostlatest.photos %>
<%= image_tag(photo.avatar.url(:news_images), :class => 'work-sample') %>
<% end %>
</div>
<p class="post-description"><%= #tynewyddpostlatest.comments.html_safe %></p><a class="post-more" href="#">Continue Reading »</a>
<div class="post-item-panel">
<ul>
<li class="date">
<p><%= date_output(#tynewyddpostlatest.published_on) %></p>
</li>
</ul>
</div>
</div>
So the historical posts go down the left hand side and the latest post goes in the center
.js.erb
<% if params[:type] == 'tynewyddnews' %>
jQuery('.post-item').html('<%= escape_javascript(render partial: 'tynewyddnewspost') %>');
<% end %>
Partial
<div class="post-item">
<h2><%= #tynewyddpost.title %></h2>
<div id="work-samples">
<% for photo in #tynewyddpost.photos %>
<%= image_tag(photo.avatar.url(:news_images), :class => 'work-sample') %>
<% end %>
</div>
<p class="post-description"><%= #tynewyddpost.comments.html_safe %></p>
<div class="post-item-panel">
<ul>
<li class="date">
<p><%= date_output(#tynewyddpost.published_on) %></p>
</li>
</ul>
</div>
</div>
Controller
def tynewyddnews
tynewyddpost = Post.tynewydd_posts.find(params[:post_id])
tynewyddpost.shift
#tynewyddpost = tynewyddpost
#tynewyddpostlatest = Post.tynewydd_posts.first
end
tynewydd_posts is a scope
scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC"
So my issue at the moment is when i try and render the page i get the error
Couldn't find Post without an ID
Apologies for the long post but if someone could point me in the right direction that would be great
Thanks
It looks to me like you're doing it way wrong, sorry. It doesn't need to be that complicated. I would start over from scratch with a much simpler example, and then build up from there.
I would do something like rails g scaffold post title:string and then do this, just in a browser console:
$.ajax({
url: "/posts/index"
}).done(function() {
console.log("done");
});
You should be able to see the data coming back through your browser's console. On the Rails side, that data is coming from here:
class PostsController < ApplicationController
def index
#posts = Post.all
# there might be more stuff here
end
end
Hopefully you understand what I'm talking about. If you don't, I'd recommend separately learning a little more about Rails and a little more about jQuery/ajax before trying to combine the two.
OK so it seems my issue was the way i was calling the id of a post and I also moved my ajax call into a separate action, setup all be it complicated is correct.
What i changed
<%= link_to t.title, tynewyddnews_path(:type => 'tynewyddnews'), :post_id => t.id, :remote => true %>
was changed to
<%= link_to t.title, my_path_path(:type => 'tynewyddnews', :id => t.id), :remote => true %>
Controller
I added a new action to handle the ajax call, finding a post by id
def my_path
#tynewyddpost = Post.find(params[:id])
end
Then in my partial I could use the #tynewyddpost instance variable
Hope this helps someone else

rails ajax request doesn't work

I have some problem with ajax
This request GET http://localhost:3000/projects/new (304 Not Modified) does work, it executes javascript from response:
$('#add-project-button').hide();
$('#project-form').append("<form accept-charset=\"UTF-8\" action=\"/projects\" class=\"new_project\" data-remote=\"true\" id=\"new_project\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"utf8\" type=\"hidden\" value=\"✓\" /><input name=\"authenticity_token\" type=\"hidden\" value=\"gzu9DETiVV8N+OtRnkdYpD6aa0/RbM7i2H+nkQ0yXGc=\" /><\/div>\n <div class=\"field\">\n <label for=\"project_name\">Name<\/label><br />\n <input id=\"project_name\" name=\"project[name]\" size=\"30\" type=\"text\" />\n <\/div>\n <div class=\"actions\"><input name=\"commit\" type=\"submit\" value=\"Create Project\" /><\/div>\n<\/form>");
But another request POST http://localhost:3000/projects (200 OK) seems ok but response is empty, no javascript is executing, but the server answer is ok:
Rendered tasks/_task.html.erb (0.0ms)
Rendered projects/_project.html.erb (4.5ms)
Rendered shared/_create.js.erb (5.4ms)
Rendered projects/create.js.erb (6.1ms)
Completed 200 OK in 96ms (Views: 8.6ms | ActiveRecord: 84.9ms)
So I'm guessing that the browser somehow is of not supposed to execute javascript from server in this case.
What might be a problem? How to make browser receive the javascript and execute it? Thanks.
UPDATE: The form which is making ajax request:
<%= form_for(#project, :remote => true) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
The controller action:
def create
#project = current_user.projects.build(params[:project])
respond_with(#project.tap(&:save))
end
Maybe the problem is causing by using partial as layout, projects/create.js.erb:
<% render :layout => '/shared/create', locals: { obj: #project } do %>
$('#project-container').append("<%= escape_javascript render(#project) %>");
$('#add-project-button').show('fast');
$('#project-form').hide('fast', function(){ $('#project-form').empty(); });
<% end %>
The problem was very simple, I forget to put <%= sign in erb, so it should be:
<%= render :layout => '/shared/create', locals: { obj: #project } do %>
$('#project-container').append("<%= escape_javascript render(#project) %>");
$('#add-project-button').show('fast');
$('#project-form').hide('fast', function(){ $('#project-form').empty(); });
<% end %>

Conditional navigation bar

Hello Guys I've a request for you.I've Drinks, Menus and Users routes.
I've this code in views/layout/application.html.erb:
<div>
<%= render "shared/navigation_bar"
</div>
How to make the navigation_bar to render in all the pages except in users pages?
I finally work around many methods, but I finally come up with a solution(not really stunnin', I must confess) , that works for me.
<div>
<% if controller.controller_name == "drinks" %>
<%= render "shared/navigation_bar" %>
<% elsif controller.controller_name == "menus" %>
<%= render "shared/navigation_bar" %>
<% end %>
</div>
The flow control doesn't include Users's controller, so the navigation_bar layout won't appear on User's pages.
That's it.If you guys have a better alternative just let me know.

Ruby on Rails 3 : Playing with views

I am sorry for my bad english. I just try to description my question. :)
I have an application layout that have a yield for display post in body. I have another yield :footerpost3 for display title of recent post on the footer.
When I in localhost:3000, the yield :footerpost3 display a recent of title correctly. but when i am click a post link, which is the url is localhost:3000/posts/3, the yield :footerpost3 display nothing.
Here is my code:
app/views/layout/application.html.erb
<!-- begin footer comment widget -->
<div class="footer_list widget_recent_comments">
<div class="title"><h5>Artikel Terkini</h5></div>
<%= yield :footerpost3 %>
</div>
<!-- end footer comment widget -->
app/views/store/index.html.erb
<% content_for :footerpost3 do %>
<% #postsMain.each do |dopostAll| %>
<div class="entry">
<ul>
<li class="recentcomments"><%= link_to dopostAll.title, dopostAll %></li>
</ul>
</div>
<% end %>
<% end %>
i hope my question is easy to understand.. :)
Looks like your root url is stores#index .
You must be initializing #postsMain in the stores#index action and generating the content_for footerpost3 in stores/index.html.erb.
When you click on a post, you will be taken to posts#show page. So you have to initialize #postsMain even in posts#show action and generate the content for footerpost3 even in posts/show.html.erb
The answer is there in your question. You are defining the "content for" footerpost3 in that block, which exists in index.html.erb. When you're on /posts/3, index.html.erb is not rendered, but rather show.html.erb is.
To solve this, you'd need to add the content in the show.html.erb template as well.
You could solve this in multiple ways. Using nested layouts would be one. For example, you might create a posts layout at app/views/layout/posts.html.erb, like so:
<% content_for :footerpost3 do %>
<% #postsMain.each do |dopostAll| %>
<div class="entry">
<ul>
<li class="recentcomments"><%= link_to dopostAll.title, dopostAll %></li>
</ul>
</div>
<% end %>
<% end %>
<%= render :file => 'layouts/application' %>
In this way, all the views of your PostsController would use this layout, which simply adds your footer content, then renders the application_layout.

Resources