In this bog we will implement display a loading gif during Ajax request processing within rails.
HTML - In the view we will do product listing of the perticular user. While product will fetched from ajax request loading gif will be display.
<div class=""><h1>Product Listing</h1></div>
<%= hidden_field_tag("user", current_user.id) %>
<div class="loader">
<i class="fa fa-refresh fa-spin fa-3x fa-fw"></i>
<span>Loading...</span>
<h2>Loading...</h2>
</div>
<div id="product_listing_div"></div>
Js - Now, we will send a ajax request to a controller's method for getting products for perticular user here we will send user params for that.
Controller -
Create a partial view - _product_listing.html.erb
<% if products.size > 0 %>
<% products.each do |product| %>
<div class="form-group">
<%= image_tag(product.image) %>
<%= product.title%>
</div>
<% end %>
<% else %>
<p>Product is not found</p>
<% end %>
Css - for loading gif
.loader{
text-align:center;
}
.loader .fa{
font-size:100px;
color:#25aae1 ;
}
That's it !!!!
HTML - In the view we will do product listing of the perticular user. While product will fetched from ajax request loading gif will be display.
<div class=""><h1>Product Listing</h1></div>
<%= hidden_field_tag("user", current_user.id) %>
<div class="loader">
<i class="fa fa-refresh fa-spin fa-3x fa-fw"></i>
<span>Loading...</span>
<h2>Loading...</h2>
</div>
<div id="product_listing_div"></div>
$(document).ready(function() {
# Here ajax request is started on page load. You can create a condition for ajax request(ex- on click method).
var user = $('#user').val();
$.get(('/product_listing'), {user: user}, function(response) {
if (response !== null) {
$('.loader').hide();
}
});
});
# Here ajax request is started on page load. You can create a condition for ajax request(ex- on click method).
var user = $('#user').val();
$.get(('/product_listing'), {user: user}, function(response) {
if (response !== null) {
$('.loader').hide();
}
});
});
Controller -
def product_listing
if request.xhr?
user = params[:user]
@products = Product.where(user: user).take
end
end
In view- Create product_listing.js.erbif request.xhr?
user = params[:user]
@products = Product.where(user: user).take
end
end
$('#product_listing_div').html("<%= escape_javascript(render :partial => "product_listing", :locals => {:products => @products}) %>")
Create a partial view - _product_listing.html.erb
<% if products.size > 0 %>
<% products.each do |product| %>
<div class="form-group">
<%= image_tag(product.image) %>
<%= product.title%>
</div>
<% end %>
<% else %>
<p>Product is not found</p>
<% end %>
Css - for loading gif
.loader{
text-align:center;
}
.loader .fa{
font-size:100px;
color:#25aae1 ;
}
That's it !!!!
Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.Ruby on Rails Online Training Bangalore
ReplyDelete