Javascript not executing after Rails redirect - javascript

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.

Related

JQuery Input Rails Form

I have a search form on my page with two buttons - "news" and "events".
I can get the Rails search function to work correctly but I don't want a search form, I want the user to press one of the two buttons and the search to be executed.
I figure this probably has to be done with JQuery so when a button is clicked, either "news" or "events" are added to the rails input form and it submits the form. Please appreciate where I'm going wrong here as the form won't submit and the search won't execute.
Application.js
$(document).on('ready page:load', function () {
$(".news-button").click(function(){
$("#search").val("news");
$("#news-search").submit();
});
$(".events-button").click(function(){
$("#search").val("event");
$("#news-search").submit();
});
});
Index.html.erb
<%= form_tag news_index_path, :method => 'get', :id => "news_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<div class="col-sm-3 sort-buttons">
<%= link_to "News", "", class: "btn btn-standard news-button" %>
<%= link_to "Events", "", class: "btn btn-standard events-button" %>
</div>
<div class="row">
<% #news.each do |n| %>
<div class="col-sm-4">
<div class="news-wrap">
<%= image_tag("#{n.image}", class: "img-responsive", alt: "Event/News Postings") %>
</div>
</div>
<% end %>
</div>
News.rb
class News < ApplicationRecord
if Rails.env.development?
def self.search(search)
if search
where('category LIKE ?', "%#{search}%")
else
scoped
end
end
end
end
News Controller:
def index
if params[:search]
#news = News.search(params[:search]).page(params[:page]).per_page(10)
else
#news = News.all.page(params[:page]).per_page(10)
end
end

Rails Dev environment with Javascript and Ajax

There's something I definitely don't understand going on in the background in dev.
I have an app which I've been developing locally on my Mac, and it has a form which makes an Ajax call "remote: true". It stopped working, no Ajax call, nothing in the logs.
The only way I could get it to start working again was to edit my _form.html.erb partial by adding a second input field (identical to the original, straight copy and paste). Refresh the page, then it worked. I've unedited my original edit, so the code is back to where it originally was (when it was not working), but now it's working.
What does the edit cause to happen? Is there someway I can cause it to happen without editing my code?
Thanks.
----- EDIT adding code -----
My form is (the text_field_tag is what I copied and pasted)
<div id="friend-lookup">
<h3>Search for friends</h3>
<%= form_tag search_friends_path, remote: true, method: :get, id: 'friend-lookup-form' do %>
<div class="form-group row no-padding text-center col-md-12">
<div class="col-md-10">
<%= text_field_tag :search_param, params[:search_param],
placeholder: "first name, last name or email", autofocus: true,
class: 'form-control search-box input-lg' %>
</div>
<div class="col-md-2">
<%= button_tag(type: :submit, class: "btn btn-lg btn-success") do %>
<i class="fa fa-search"></i> Look up a friend
<% end %>
</div>
</div> <!--- form-group -->
<% end %>
<%= render 'common/spinner' %>
<% if #users %>
<% if #users.size > 0 %>
<div id="friend-lookup-results" class="well results-block col-md-10">
<table class="search-results-table col-md-12">
<tbody>
<% #users.each do |user| %>
<tr>
<td><strong>Name:</strong> <%= user.full_name %></td>
<td><strong>Email:</strong> <%= user.email %></td>
<td><strong>Profile:</strong> <%= link_to "View Profile", user_path(user),
class: "btn btn-xs btn-success" %>
<% if current_user.not_friends_with?(user.id) %>
<%= link_to "Add as my friend", add_friend_path(user: current_user, friend: user),
class: "btn btn-xs btn-success", method: :post %>
<% else %>
<span class="label label-primary">
You are friends
</span>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% else %>
<p class="lead col-md-12">
No people match this search criteria
</p>
<% end %>
<% end %>
<div id="friend-lookup-errors"></div>
</div>
And the javascript is
# assets/javascript/friends.js
var init_friend_lookup;
init_friend_lookup = function() {
$('#friend-lookup-form').on('ajax:before', function(event, data, status){
$('#friend-lookup-results').replaceWith(' ');
show_spinner();
});
$('#friend-lookup-form').on('ajax:after', function(event, data, status){
hide_spinner();
});
$('#friend-lookup-form').on('ajax:success', function(event, data,status){
$('#friend-lookup').replaceWith(data);
init_friend_lookup();
});
$('#friend-lookup-form').on('ajax:error', function(event, xhr, status, error){
hide_spinner();
$('#friend-lookup-results').replaceWith(' ');
$('#friend-lookup-errors').replaceWith('Person was not found.');
});
}
$(document).ready(function() {
init_friend_lookup();
});
You may be used to installing JavaScript behavior in response to the window.onload, DOMContentLoaded, or jQuery ready events. With Turbolinks, these events will fire only in response to the initial page load—not after any subsequent page changes.
Change the "ready" event for 'turbolinks:load', and repeat the same step with you all events.
$(document).on('turbolinks:load', function () {
init_friend_lookup();
});
Read the documentation, https://github.com/turbolinks/turbolinks
Maybe this will help someone out there.
I am running Rails 5.
What was tricky was that it seemed intermittent.
My problem seems to be turbolinks related. Removing turbolinks, in javascript/application.js
//= require turbolinks
seems to have fixed the problem consistently.

Rendering a partial to an edit form inside a popover in rails 4

Hi guys I really need help here.
I'm making a todo app and displaying each task through an iteration. Next to each task I have a pencil glyphicon.
When I click on it, I want there to be a popover containing an edit form and edit the task on the spot. I'm having a ton of troubling rendering that form.
***** UPDATE *****
Clark helped me get the popover to work. But The form inside the popover is acting like a link instead of a form so I can't type in the text area.
This is my index.html.erb
<div id='user_tasks'>
<% #tasks.each do |task| %>
<ul>
<li>
<%= task.description %>
<%= link_to edit_task_path(task), :rel => 'popover', method: 'get', remote: 'true' do %>
<span class = 'edit_task_<%=task.id%> glyphicon glyphicon-pencil'> </span>
<% end %>
</li>
</ul>
<% end %>
</div>
This is the edit.js.erb
$(function(){
$('.edit_task_<%=#task.id%>').popover({
html: true,
title: 'edit',
content: <%= escape_javascript render 'edit_form', task:#task %>
}).popover('show'); });
and my controllers look like this:
def index
#new_task= Task.new
#tasks= Task.all
end
def create
#new_task= Task.new(task_params)
#task.save
redirect_to :back
end
def edit
#task= Task.find(params[:id])
end
_edit_form.html.erb looks like this: This isn't the edit form that I plan to use. Its just a copy of the create task form. I plan to fix it once I get the popover working.
<%= form_for task, :html=>{:class=> 'form-inline'} do |f| %>
<div class='form-group'>
<%= f.text_field :description, placeholder: 'create a task' %>
<%= button_tag(type:'submit', class:"btn btn-default btn-xs") do %>
<span class='glyphicon glyphicon-plus'></span>
<% end %>
</div>
<% end %>

Follow button using AJAX only updates first div

I have a _user.html.erb partial that I am rendering on my Users#Index action with a form embedded to allow following and unfollowing of each user. I also have accompanying create.js.erb and destroy.js.erb files in my relationships controller to handle the AJAX. Right now I have to refresh the page in order to see the changes made by clicking the "follow/unfollow" button next to a users name except the first user's record behaves correctly.
_user.html.erb
<div id ="follow_form">
<% if current_user.following?(user) %>
<%= form_for(current_user.relationships.find_by(followed_id: user.id),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>
<% else %>
<%= form_for(current_user.relationships.build(followed_id: user.id),
remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
<% end %>
create.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= #user.followers.count %>')
destroy.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>")
$("#followers").html('<%= #user.followers.count %>')
here is a link to my users_controller.rb https://gist.github.com/anonymous/9608208 and my relationships_controller.rb https://gist.github.com/anonymous/9608284
I've tried changing the div to something dynamic like
<div id ="follow_form_<%= user.id %>">
But when I make the same change to the javascript like this
$("#follow_form_<%= user.id %>").find.html("<%= escape_javascript(render('users/unfollow')) %>")
it doesn't seem to work.
I've been trying to figure out how to pass the user.id attribute into the javascript but am falling flat.
It turns out the problem was in my _follow_form.html.erb partial.
I had to change
<div id="follow_form">
to
<div id="follow_form_<%= #user.id %>">
I thought I only needed to make the change in the _user.html.erb partial but I was wrong. My current user partial uses the same div id to contain the button in the Users#Index view
<div id ="follow_form_<%= user.id %>">

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

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

Categories