AJAX using rails: first item does not get updated on cart - ajax

I have just started learning Ruby on Rails using Agile Web Develop ment by Sam Ruby. I'm currently stuck on task F: adding Ajax to cart. Everything went well till the time I added to the code for hiding an empty cart. Now when I add the first item the cart shows up empty on the side bar (it should show up with one item n the cart) but when i add the second item the cart shows up with 2 items, as it should.The code works if I add more items. I'm facing the problem only when adding the first item on the cart. I've been tearing my hair out for a day now on this problem. Any help will be greatly appreciated. Apologies if I haven't furnished complete details. Please let me know the additional details, if any, that would be relevant. I'm using rails 3.2.8 and ruby 1.9.3 Thanks!
_cart.html.erb
<div class="cart_title">Your Cart</div>
<table>
<%= render(cart.line_items) %>
<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(cart.total_price) %></td>
</tr>
</table>
<%= button_to 'Empty Cart',cart, method: :delete, confirm: 'Are you sure?'%>
_line_item.html.erb
<%if #current_item==line_item%>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td><%= line_item.quantity %> ×</td>
<td><%= line_item.product.title %></td>
<td class="item_price" ><%= number_to_currency(line_item.total_price) %></td>
<td><%= button_to 'Remove Item', line_item, method: :delete, confirm: 'Are you sure?'%>
</tr>
create.js.erb
$("#notice").hide();
if ($('#cart tr').length > 0) { $('#cart').show('blind', 1000); }
$('#cart').html("<%=j render #cart %>");
$('#current_item').css({'background-color':'#88cc88'}).
animate({'background-color':'#114411'}, 1000);
application.js.erb
<html>
<head>
<title>Pragprog Books Online Store</title>
<!-- START:stylesheet -->
<%= stylesheet_link_tag "scaffold" %>
<%= stylesheet_link_tag "depot", :media => "all" %><!-- <label id="code.slt"/> -->
<!-- END:stylesheet -->
<%= javascript_include_tag "application" %>
<%= csrf_meta_tag %><!-- <label id="code.csrf"/> -->
</head>
<body id="store">
<div id="banner">
<%= image_tag("logo.png") %>
<%= #page_title || "Pragmatic Bookshelf" %><!-- <label id="code.depot.e.title"/> -->
</div>
<div id="columns">
<div id="side">
Home<br />
Questions<br />
News<br />
Contact<br />
<%if #cart%>
<%= hidden_div_if(#cart.line_items.empty?, id:"cart") do%>
<%=render #cart%>
<% end %>
<% end %>
</div>
<div id="main">
<%= yield %><!-- <label id="code.depot.e.include"/> -->
</div>
</div>
</body>
</html>
~

managed to solve it myself :)..while typing out the problem i got a hint that the problem was somehow with the rendering itself and so it was .. the solution is to set the show parameter to 0 in { $('#cart').show('blind', 1000); } the code should now be { $('#cart').show('blind', 0); }
#Btuman done!!

Related

Ransack Search Ajax in Application Layout Rails

I have a Rails 4.2 app in which I'm using Ransack mixed with Geocoder for search. I want to use an Ajax (remote: true) for my search to avoid pageloads and changing of the URL.
When I implement this in my index view it works great, but I want to abstract the search box to the application layout file so it's available site wide instead of just on the index view. When I do this (see code example) I'm able to search just fine, but the problem is I can't seem to figure out how to get the Ajax/Remote: True to work. Here is my code:
application.html.erb
<%= search_form_for(#search, url:"/resources", :method => :get, remote: true) do |f| %>
<%= text_field_tag :location, params[:location], placeholder: "Houston, TX", class: "input-sm form-control" %>
<%= f.submit "Find", class:'btn btn-sm btn-info' %>
<% end %>
application_controller.rb
before_action :build_search
private
def build_search
if params[:location].present?
#search = Resource.near(params[:location], 100).search(params[:q])
else
#search = Resource.search(params[:q])
end
end
resources/index.js.erb
$("#mapdisplay").html("<%= escape_javascript render("map") %>");
$("#results").html("<%= escape_javascript render("results") %>");
resources/index.html.erb
<div id="mapdisplay">
<%= render 'map' %>
</div>
<div id="results">
<%= render 'results' %>
</div>
resources_controller.rb
before_action :set_search_results, only: [:show, :index, :new]
def index
#hash = Gmaps4rails.build_markers(#resources) do |resource, marker|
marker.lat resource.latitude
marker.lng resource.longitude
end
respond_to do |format|
format.html {}
format.js {}
end
end
private
def set_search_results
#resources = #search.result(distinct: true)
end
resources/_map.html.erb
<script src="//maps.google.com/maps/api/js?v=3.13&sensor=false&libraries=geometry" type="text/javascript"></script>
<script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js' type='text/javascript'></script>
<h4>Resources</h4>
<div id="search">
<%= render 'search' %>
</div>
<div class="pull-right">
<%= link_to "Add", new_resource_path, class: 'btn btn-info btn-medium' %>
</div>
<div style='width: 800px;'>
<div id="map" style='width: 800px; height: 400px;'></div>
</div>
<script>
handler = Gmaps.build('Google');
handler.buildMap({
provider: {
disableDefaultUI: true
// pass in other Google Maps API options here
},
internal: {
id: 'map'
}
},
function(){
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
}
);
</script>
resources/_search.html.erb
<div class="form-group">
<%= search_form_for(#search, :id => "resource_search", remote: true) do |f| %>
<%= text_field_tag :location, params[:location], placeholder: "Houston, TX", class: "input-sm form-control" %>
<%= f.submit "Find", class:'btn btn-sm btn-info' %>
<% end %>
</div>
resources/_results.html.erb
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<% #resources.each do |r| %>
<tr>
<td><%= link_to "#{r.name}", r %></td><td><%= r.address %></td><td><%= r.notes %></td>
</tr>
<% end %>
</tbody>
</table>
Again, I can get this working in the index view/controller with js and remote: true but when I implement the search box sitewide in the application layout file I cannot use JS/remote: true.
I'm sure I'm missing something simple in my implementation so if anyone has any advice, please let me know. If my question and/or code examples are not clear let me know and I'll explain in further detail.

Value is not submitting in using Rails ajax form

I want to store value in db using Rails ajax form but it is not storing anything.Please let me to know where i did the mistake and help me to resolve this issue.
I am explaining my code below.
users/index.html.ebr:
<script type="text/javascript">
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
console.log('hello')
$.ajax({
type: "POST",
url: $(this).attr('create'), //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
});
</script>
<p><%= flash[:notice] %></p>
<%= form_for :user do |f| %>
<p>
Name : <%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
Email : <%= f.email_field :email,placeholder:"Enter your email" %>
</p>
<p>
Content : <%= f.text_field :content,placeholder:"Enter your content" %>
</p>
<p>
<%= f.text_field :submit,:onchange => "this.form.submit();" %>
</p>
<% end %>
<div id="sdf-puri" style="display:none" >
</div>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#user=User.new
respond_to do |format|
format.html
format.js
end
end
def create
#user=User.new(params[:user])
if #user.save
flash[:notice]="user created"
end
end
end
create.js.erb
$("#sdf-puri").css("display", "block");
$("#sdf-puri").html("<%= escape_javascript (render 'table' ) %>");
$("#sdf-puri").slideDown(350);
create.html.erb
<%= render 'table' %>
_table.html.erb
<table>
<tr>
<th>Name :</th>
<th>Email :</th>
<th>Content :</th>
</tr>
<% #user.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= user.content %></td>
</tr>
<% end %>
</table>
After submit value should display in same index page.Please help me.
Rails has a built in Ajax system, on your form you need to add remote: true
form_for(#user, remote: true) do |f|
This tells rails to submit the form using Ajax under the hood... You don't need all of the script above the form
Your controller already correctly has the line:
responds_to js
So all you would do is have a create.js file in your views/user folder that handled your return Ajax stuff such as appending or fading etc
you need to add remote: true in form tag

Database values are not showing inside the table while using Ajax in Rails 3

I want to display the database values inside the table using Ajax in Rails.bou i got the following error.
Error:
Template is missing
Missing template users/search, application/search with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "c:/Site/demo2/app/views"
I also added the search.html.erb i removed the error but got the blank page.
Please check my below codes.
views/users/index.html.erb
<%= form_for :user ,:url => {:action => "search" }, remote: true do |f| %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :receipt,:class => "form-control",placeholder:"user number",:onchange => "this.form.submit();" %>
</div>
<% end %>
<div id="search-output-table">
<%= render partial: "search_output_table", locales: {user: #user} %>
</div>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#user=User.new
end
def search
#user = User.find_by_receipt(params[:user][:receipt])
end
end
views/users/_search.js.erb
$("#search-output-table").html("<%= escape_javascript( render(partial: "search_output_table") ) %>");
views/users/_search_output_table.html.erb
<table>
<tr>
<th>User Name</th>
<th>User Email</th>
<th>User Number</th>
</tr>
<tr>
<td><%= #user.name %></td>
<td><%= #user.email %></td>
<td><%= #user.receipt %></td>
</tr>
</table>
I also want remove onchange event and as soon as the value will fill inside text field the action will execute without reload the page as well as the table value will display(initially the table should remain disable/hide).Please help me to resolve this error and add this new scenario.
Well, on request to UsersController#search Rails will by default render app/views/users/search.html.erb, which I assume is empty.
You probably just need to rename views/users/_search.js.erb to views/users/search.js.erb and add following to the controller
def search
#user = User.find_by_receipt(params[:user][:receipt])
respond_to do |format|
format.js
end
end
Also make sure you're passing in #user to the search_output_table template. Like this
render partial: 'search_output_table', locals: {user: #user}
And in 'search_output_table' you should use just user instead of #user.

my final step in the rails app, how to make comments appear in a popup?

This is the last remaining item to complete my first rails app and need some help.
On each user profile (localhost:3000/users/username), there's a listing of posts that the user has made. Associated with each post are comments. So post_id: 3 could have comments.
I have it working already in view form but I need the comments to appear in a popup instead when the "Comments" link under each post is clicked.
I have already applied facebox which is a jQuery-based lightbox that displays popups.
I just need to move what's currently shown in show.html.erb into a popup.
There's the _comment_form.html.erb which renders into _post.html.erb
<%= link_to #, :rel => "facebox-#{post.id}" do %>
+<%= post.comments.count.to_s %>
<% end %>
<div class ="ItemComments"><% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= image_tag("http://www.gravatar.com/avatar.php?gravatar_id=#{Digest::MD5::hexdigest(comment.user.email)}" %>
<span class="users"><%= link_to comment.user.name, comment.user %></span>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %></div>
The above renders into _post.html.erb using:
<%= render 'shared/comment_form', post: post if signed_in?%>
Then it renders into show.html.erb
I'm trying to use this line, but what do I link it to?
<%= link_to #, :rel => "facebox-#{post.id}" do %>
+<%= post.comments.count.to_s %>
<% end %>
This is shared/_comment.html.erb
<% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= image_tag("http://www.gravatar.com/avatar.php?gravatar") %>
<%= link_to comment.user.name, comment.user %>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %>
One way of doing this is to render your comments into a hidden div and give that div an id. Next you point your link to the id of the div using # followed by the id. It would look something like this:
_post.html.erb
<%= link_to "#comments", :rel => "facebox" do %>
<%= post.comments.count.to_s %>
<% end %>
<div id="comments">
<%= render 'shared/comment_form', post: post if signed_in?%>
</div>
CSS
#comments {
display: none;
}
See the 'Divs' heading over at the Facebox docs.

Ajax : data retrieving in rails3 + formtastic

I have successfully tried ajax saving in my sample formtastic with ajax form.
The new value is added to the database. But the the problem is in retrieving the list from the database as soon as i save via ajax.
How to do it.?
As soon as I add a new record I want my displaying list to be update. Both the option to add new record and list the data from database is in same page
This is my Index page. The controller and all other created via scaffolding
<h1>Listing samples</h1>
<table>
<tr>
<th><%=t :Name%></th>
<th></th>
<th></th>
<th></th>
</tr>
<% #samples.each do |sample| %>
<tr>
<td><%= sample.name %></td>
<td><%= link_to 'Show', sample %></td>
<td><%= link_to 'Edit', edit_sample_path(sample) %></td>
<td><%= link_to 'Destroy', sample, :method => :delete, :data => { :confirm => 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Sample', new_sample_path %>
<br /><br /><br /><br /><br />
<%= semantic_form_for #sample1,:url => samples_path, :remote => true do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :as => :input %>
<% end %>
<% end %>
When you save via ajax, you may have to change the way your controller responds, kinda like this:
def create
# stuff
respond_to do |format|
format.js
end
end
When you do this, rails would expect you to have created a file named create.js.erb, in which you can manipulate the data of your view(append new content to your table, render a whole new partial with your new object list, etc):
$('#your_list').html(
"<%= escape_javascript(render('your_table_partial')) %>"
);
Or
$('#your_list').append(
"<%= escape_javascript(render('your_item_of_the_table_partial')) %>"
);
These are just examples, i don't know your code enough to write the correct code for you, but you sure can use these as a base for your work.
I did the CRUD operation using these guidelines and it worked perfect
http://stjhimy.com/posts/07-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript

Resources