Jquery mobile navbar not active after session log in (Rails) - javascript

1) This is my Login page:
<% provide(:title, 'Sign In') %>
<div data-role="page" data-url="/signin/">
<h1>Sign In</h1>
<%= form_for(:session, url: sessions_path) do |f| %>
<div>
<%= f.text_field :username_or_email, placeholder: "username or email", autofocus: true %>
</div>
<div>
<%= f.password_field :password, placeholder: "password" %>
</div>
<div>
<%= f.submit "Sign In", rel: "external" %>
</div>
<% end %>
</div>
2) This is my Home page after login:
<% provide(:title, #user.name) %>
<div data-role="page" id="home" data-url="/users/<%= #user.id %>/" >
<div data-role="header">
Menu
<h4>Home</h4>
<%= link_to 'New', new_pin_path, rel: "external" %>
</div>
<% if !#user.pins.any? %>
<h3>Welcome to Pins!... Enter your first pin.</h3>
<% end %>
<%= render #user.pins %>
</div>
<div data-role="page" id="menu">
<div class="ui-grid-a center">
<div class="ui-block-a menublock">
Home
</div>
<div class="ui-block-b menublock">
<%= link_to 'Friends Pins', pins_path %>
</div>
<div class="ui-block-a menublock">
<%= link_to 'Settings', edit_user_path(current_user) %>
</div>
<div class="ui-block-b menublock">
<%= link_to "Sign Out", signout_path, method: "delete" %>
</div>
</div>
</div>
So basically, after I log in and try clicking on Menu I get no response (unless I refresh the page).
3) This is how my session login works:
I was going to paste it but it's super long, I basically used the same thing that is going on here:
http://ruby.railstutorial.org/chapters/sign-in-sign-out#top
4) Trailing slashes (this is a requirement by jQuery Mobile): I thought my problem may be because I did not have trailing slashes set on all the urls, so I added this to my application.rb: config.action_controller.default_url_options = { :trailing_slash => true } And although it fixed a lot of the navigation between pages, it does not fix the issue after my session log in.
5) Also note that when I refresh the home page after login, the navbar does work correctly.

You are missing a "data-rel" tag. Try the following:
Menu

Related

Ruby on Rails on rendering with Ajax

I am working on a simple website which has posts in forms of songs, now I have implemented like and dislike feature, but when I click on like/dislike it renders the numbers of likes/dislikes on all posts. And when I reload the page it returns them to normal. Now I would like it to change only the numbers for that particular post, without affecting the numbers on other posts?
My view for posts:
<div class="col-6">
<% for #s in #songs %>
<div class="card border-secondary mb-1">
<div class="card-header">
<div class="col-1">
<%= image_tag User.find(#s.user_id).user_image.url, :size=>"50x50" %>
</div>
<div class="col-11 text-muted">
<a href="/user/<%= User.find(#s.user_id).username %>" class="info-col">
<%= User.find(#s.user_id).username %>
</a>
- <%= #s.created_at.to_formatted_s(:short) %>
</div>
</div>
<div class="card-body">
<h4 class="card-title">
<%= #s.title %>
</h4>
<p class="card-text"><%= simple_format(#s.content) %></p>
</div>
<div class="card-footer text-muted">
<div class="col-12">
<div class="row">
<div class="col-3" id="song_like">
<%= render '/components/song_like' %>
</div>
<div class="col-3" id="song_dislike">
<%= render '/components/song_dislike' %>
</div>
<div class="col-4" id="song_comment">
<%= render '/components/song_comment' %>
</div>
</div>
</div>
</div>
</div>
<% end %>
</div>
The song_like partial has the following code:
<%= link_to like_song_path(#s.id, like: true), remote: true, method: :post do %>
<i class="fa fa-thumbs-o-up fa-lg" aria-hidden="true"></i> &nbsp <span class="songlikes">
<%= #s.thumbs_up_total %>
</span>
<% end %>
The song_dislike partial has the following code:
<%= link_to like_song_path(#s.id, like: false), method: :post, remote: true do %>
<i class="fa fa-thumbs-o-down fa-lg" aria-hidden="true"></i> &nbsp <span class="songdislikes">
<%= #s.thumbs_down_total %>
</span>
<% end %>
And my 'like' controller is like:
def like
#s = Song.find(params[:id])
#like = Like.create(like: params[:like], user: current_user, song: #s)
respond_to do |format|
if #like.valid?
format.html
format.js
else
format.html
format.js
end
end
end
This is how like.js.erb looks like:
$('.songlikes').html("<%= #s.thumbs_up_total %>");
$('.songdislikes').html("<%= #s.thumbs_down_total %>");
Here is the part of routes.rb file:
resources :songs do
member do
post 'like'
end
end
I am assuming there is some issue on rendering or jquery, but can't figure it out. Do You have any instructions?
EDIT: You should remove the redirect_to in your f.html?
This reloads the page - and the js will therefore not work.
An Ajax call is per definition not reloading the page.
If you remove those lines and try the following:
There's no new data in your jQuery.
You need a global attribute, so the view can find the data from your controller.
For example:
#like = ...
Then in your view you can add a local to be rendered:
$("#song_like").load("<%=j render partial: '/components/song_like', locals: {like: #like} %>");
But, you need to change your partial to be a partial. And change the variable to like so it will be rendered in the right way.
Hope it helps!
UPDATE
If you want to hit a specific song you can render it with each and then assign an id to your post's class
For example:
<% #posts.each do |post| %>
<div class="post-content">
... other stuff ...
<div class="likes like-post-<%= post.id %>">
.. number of likes
</div>
<%= link_to "Like", link_route_path(post) %>
</div>
<% end %>
# controller
# So you can use the id in your js view
#id = params[:id]
# view.js
$(".like-post-" + "<%= #id %>").html("<%= #s.thumbs_up_total %>");
Hope the idea helps.
change rendering like this:
<div class="col-3" id="song_like">
<%= render partial: '/components/song_like', locals: {s: #s, like: true} %>
</div>
then in partial:
<%= link_to like_song_path(s.id, like: like), method: :post, remote: true do %>
<i class="fa fa-thumbs-o-up fa-lg" aria-hidden="true"></i> &nbsp <%= s.thumbs_up_total %>
<% end %>
and in controller of like_song
should define
#s= Song.find(params[:id])
like = Like.create(like: params[:like], user: current_user, song: #song)
#like = !like.like # opposite to your current status
rest of the things good and then in like.js.erb
$('#songs_like').html("<%= escape_javascript(render partial: '/components/song_like', locals: { s: #s, like: #like } ) %>")

Javascript not executing after Rails redirect

My application contains a very simple login and two separate AJAX calls. I have a loading spinner that is hidden automatically whenever a page is ready it is contained in index.js
$(function() {
$("loading").hide();
$("#scan_button").on("ajax:success", function(e, data, status, xhr) {
$("#standard_results").hide();
$("#results").show();
$("#results").html(data);
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
$(document).ajaxStart(function() {
$('#loading').show();
});
});
When a user logs in the following happens
class SessionController < ApplicationController
def create
user = User.find_by(username: params[:session][:username])
if(user.password == params[:session][:password])
log_in user
redirect_to root_path
end
end
def destroy
logout
redirect_to root_path
end
end
The route path takes me back to 'home#index' for which the index.js file exists. When the user logs in the redirect happens and the loading spinner is hidden and all JavaScript executes as expected.
When the user hits log out however the redirect occurs, but the loading spinner is shown and no JavaScript ever gets executed. Here is my index.html.erb file that contains the JavaScript.
<% content_for :title, "Network Monitor" %>
<div class="container-fluid">
<nav class="navbar narvbar-dark bg-inverse">
<span class="navbar-brand">Network Monitor</span>
<%= link_to "Scan", scan_path, remote: true, class: "btn btn-secondary", id: "scan_button" %>
<% if logged_in? %>
<span class="pull-xs-right"><%= link_to "Logout", logout_path, class: "btn btn-secondary" %></span>
<% else %>
<%= form_for(:session, url: login_path, :html => {:class => 'form-inline pull-xs-right'}) do |f| %>
<%= f.text_field :username, class: 'form-control', placeholder: "Username" %>
<%= f.password_field :password, class: 'form-control', placeholder: "Password" %>
<%= f.submit "Log in", class: 'btn btn-primary', id: 'login_button' %>
<% end %>
<% end %>
</nav>
<div id="loading">
<%= image_tag "loading.gif", class: "loading_gif" %>
</div>
<div class="row">
<div class="col-md-12">
<div id="scan_bar">
<h3>Welcome to your network monitor!</h3> <br />
<p>To get started hit the scan button in the top right corner, this will detect the computers that are alive on your network and show them below.</p>
</div>
</div>
</div>
<div class="row">
<div id="results">
</div>
<div id="standard_results">
</div>
Solved. It was as simple as using
$(document).on('turbolinks:load', function() {});
Instead of what I had posted, this seems to be the way that Rails 5 and turbolinks want you to use, and it worked.
According to the
turbolinks document, I use the event page:change to solve the problem:
$(document).on("page:change", function(){...});
It works for me.
In case others run into this. If you are using an href or link_to try doing something like this:
<li><%= link_to "Home", jobs_path, method: :get %></li>
...where you specify the get method in the request.

Use Jquery to show form when clicking "Add Object" button in Rails app

I'm trying to make an "Add Car" button that when clicked shows the form that the user uses to add a car to their profile. I think I have the jQuery right, but I'm unsure of how to connect the button id and form to the script to make it work right. I currently have:
home.html.erb
<div class="row">
<aside class="col-md-4">
<section class="user_info" %>
<%= render 'shared/user_info' %>
</section>
<%= link_to "Add Car", shared/car_form, id: "add", class: "btn btn-lg btn-primary" %> //button that I want to hide/show the form
<section class="car_form">
<%= render 'shared/car_form' %> // current version that shows the form without having to click a button
</section>
</aside>
<div class="col-md-8">
<h3>My Cars</h3>
<%= render 'shared/feed' %>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('shared/car_form').hide(); // inserted form id, hides form
$('add').click(function() { // inserted button id
$('shared/car_form').show(); // inserted form id, shows form
});
});
</script>
And here is the car form, located in the "shared" folder
_car_form.html.erb
<%= form_for(#car, html: {multipart: true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<h3> Add Your Car</h3>
<div class="field">
<%= f.text_area :year, placeholder: "Year i.e. '1993" %>
<%= f.text_area :brand, placeholder: "Brand i.e. 'Ford'"%>
<%= f.text_area :model, placeholder: "Model i.e. 'Mustang'" %>
<%= f.text_area :vin, placeholder: "17 digit VIN number" %>
<%= f.text_area :mileage, placeholder: "Current Car Mileage" %>
</div>
<%= f.submit "Add Car", class: "btn btn-primary" %>
<span class="picture">
<%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
</span>
<% end %>
<script type="text/javascript">
$('#car_picture').bind('change', function() {
size_in_megabytes = this.files[0].size/1024/1024;
if (size_in_megabytes > 5) {
alert('Maximum file size is 5MB. Please choose a smaller file.');
}
});
</script>
jQuery has been added to the gem file and installed. Need help implementing it.
$('.btn-primary').on('click',function(evt) {
$('.car_form').show();
});

Rails showing series of objects with form_for and Ajax

I'm trying to show a list of "Interests" that users can "follow" by clicking on a button associated with the Interest's image. Upon clicking the button to follow an Interest, the Interest (and it's corresponding image) should disappear from the list.
I'm using a hide function in a create.js.erb file called upon by a Relationship controller when the follow button is clicked, but the function will only hide the first Interest in the series of Interests--NOT the Interest the user clicked on that needs to disappear. So there has to be a better way to set this up, but I cannot, for the life of me, figure it out. Here's my current setup:
My Controller
class StaticPagesController < ApplicationController
def home
#user = current_user
#city = request.location.city
#interests = Interest.all
end
The home page
<%= render #interests %>
The partial
<div id="follow_form">
<div class="four columns portfolio-item interests">
<div class="our-work">
<a class="img-overlay">
<%= image_tag interest.image_path %>
<div class="img-overlay-div">
<h4><%= interest.name %></h4>
</br>
<h5>Placeholder
</br>
<%= interest.desc %></h5>
<%= form_for(current_user.relationships.build(followed_id:
interest.id), remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "I'm interested", class: "b-black" %>
<% end %>
</div>
</a>
<h3><%= interest.name %><span>features info</span></h3>
</div>
</div>
</div>
And the create.js.erb that's called upon by a Relationships controller when you click the button:
$("#follow_form").hide();
UPDATE
Here is the Relationships controller for additional clarification
def create
#interest = Interest.find(params[:relationship][:followed_id])
current_user.follow!(#interest)
respond_to do |format|
format.html { redirect_to(root_url) }
format.js
end
end
You need to provide something to differentiate the different "follow_forms" that you have on the same page. Otherwise, jQuery will just select the first element and only remove that one.
One idea of how to do this would be to append the "interest.id" to the end of the follow_form id
Update your partial to be like this (assuming your partial is called and located in /app/views/interests/_follow_form.html.erb:
<div id="follow_form<%="#{interest.id} %>">
<div class="four columns portfolio-item interests">
<div class="our-work">
<a class="img-overlay">
<%= image_tag interest.image_path %>
<div class="img-overlay-div">
<h4><%= interest.name %></h4>
</br>
<h5>Placeholder
</br>
<%= interest.desc %></h5>
<%= form_for(current_user.relationships.build(followed_id:
interest.id), remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "I'm interested", class: "b-black" %>
<% end %>
</div>
</a>
<h3><%= interest.name %><span>features info</span></h3>
</div>
</div>
</div>
This way each follow_form will have a unique ID attached to it. Then you can loop through your interests and call a partial on each one like this:
home page:
<% #interests.each do |interest| %>
<%= render 'interests/follow_form', :interest => interest %>
<% end %>
create.js.erb
$("#follow_form_<%= "#{#interest.id}" %>").hide())
Your controller action can stay the same.

Rails 3 coffeescript controller association?

Alright, I'm a JS / JQuery / Coffeescript noob. This is probably easy points for someone.
Having successfully implemented RBate's Nested Form Model railscast, I am attempting to reproduce this in a simpler model: Chapters have many counties.
I have a chapters.js.coffee file with the following code:
jQuery ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('#destroy').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
This code works just fine in the other model. But not here.
_chapters_form.html.erb:
<div class="row span12">
<%= form_for(#chapter) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="span2"><strong>Chapter name:</strong></div>
<div class="span6"><%= f.text_field :name %></div>
<div class="span2"><strong>Chapter Number:</strong></div>
<%= f.number_field :chapter_num, class: "span2" %>
</div>
<div class="row span12">
<div class="span12">
<%= f.fields_for :counties do |builder| %>
<%= render 'county_fields', f: builder %>
<% end %>
</div>
<% if f.object.new_record? then link = 'Add the Chapter' else link = 'Update Chapter' end %>
<%= f.submit "#{link}", class: "btn btn-large btn-primary" %>
<%= link_to "Cancel", chapters_path, class: "btn btn-large btn-primary" %>
<% end %>
</div>
and:
_county_fields.html.erb:
<fieldset>
<div class="well span12">
<div class="row span12">
<div class="span3">County Number: <br /><i>(6-digit FIPS code)</i></div>
<div class="span2"><%= f.number_field :county_num %></div>
<div class="span2">County Name:</div>
<div class="span5"><%= f.text_field :name %></div>
</div>
<div class="row span12"><hr></div>
<div class="row span12">
<div class="span6">Move to new Chapter:</div>
<div class="span6"><%= select(:county, :chapter_id, Chapter.all.collect {|c| [c.name, c.id]}) %></div>
</div>
<div class="row span12">
<div class="pull-right">
<%= f.hidden_field :_destroy, id: "destroy" %>
<%= link_to "remove county", "#", class: "remove_fields" %>
</div>
</div>
</div>
</fieldset>
There are no errors in the JS. Again, noob speaking, but it doesn't seem that the JS is getting called. Clicking <%= link_to "remove county", "#", class: "remove_fields" %> just adds the # to the URI.
What am I doing wrong?
As requested, the HTML in a fiddle which doesn't work either.
Your HTML is broken. You open a div before the form element, then close it before you close the form. If you move the form element up to just inside the container div, it works.
<body>
<div class="container-fluid">
<form accept-charset="UTF-8" action="/chapters/7" class="edit_chapter" id="edit_chapter_7" method="post">
<div class="row-fluid">
...
</div>
</form>
</div>
</body>
You should take more care in the indenting of your HTML to help avoid this sort of simple mistake. Code format matters.
The page on which they appear - regardless of how they are rendered - must be an action of the chapters_controller for chapters.js.coffee to be included. My bet is that the script is not being included at all, as the code looks fine. Check out the pages you are having issues with with this code:
jQuery ->
console.log "included chapters.js.coffee"
$('form').on 'click', '.remove_fields', (event) ->
console.log "clicked .remove_fields"
$(this).prev('#destroy').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
Also, post up the rendered HTML in your question

Categories