The submit button works only for validating the javascript in the question.js file, but it doesnt do the basic function, which is submiting the form itself! Your help is very appreciated.
`Ruby page code containing the form element
<script type="text/javascript">
loadScript("/javascripts/questions.js",function() {});
</script>
<h1 class="hdr1">Ask question</h1>
<%= link_to Profile.find(session[:user_id]).firstname,{},{:id=>"person"} %>
<% form_for(#question) do |f| %>
<%= f.error_messages %>
<br>
<table id="newQuesTable" width="100%" cellpadding="5" border="1">
<tr>
<td width="25%"><label>Your Question </label> - </td>
<td><%= f.text_area :content, :rows=>5, :cols=>35, :maxlength=>500, :id=>"newQuesTxtA"%> </td>
<td width="30%"><i><label id="newQuesLabel" style="color:red;background-color:yellow;visibility:visible;"></label></i></td>
</tr>
<tr>
<td width="25%"><%= f.label :tags %> -</td>
<td><%= f.text_field :tags, :maxlength=>48, :id=>"tagsNewQuesTxt" %></td>
<td width="30%"><i><label id="nquesTagsLabel" style="color:red;background-color:yellow;visibility:visible;"></label></i></td>
</tr>
<tr>
<td>Question Scope -</td>
<!--the open id for the hierarchy comes here-->
<!-- the select box comes here -->
<td> <%= f.text_field :ID_string %></td>
</tr>
</table>
<br>
<%= f.submit 'Post Question' %> <%= f.submit 'Cancel', :id=>'docNewCancelButton', :type=>'reset' %>
<% end %>
<br>
<hr>
<br>
<%= link_to 'Back', questions_path %>
Javascript code present in question.js file
Event.observe(window, 'load', function(){
$('new_question').observe('submit', submitQuestionCreate);
$('quesNewCancelButton').onClick('resetquesform')
});
function resetquesform()
{
event.preventDefault();
reset($('new_question'));
return;
}
function submitQuestionCreate(event)
{
//event.preventDefault();
var quesfield = $('newQuesTxtA');
var tagsfield = $('tagsNewQuesTxt');
var labelnques = $('newQuesLabel');
var labelnquestags = $('nquesTagsLabel');
if((quesfield.value == "") && (tagsfield.value == ""))
{
event.preventDefault();
//alert('Question and Tags field cannot be empty');
labelnques.innerHTML = 'Question field cannot be empty!';
labelnquestags.innerHTML = 'Please enter (some) relevant tags...';
probchk = true;
return;
}
if((quesfield.value == "") || (tagsfield.value == ""))
{
event.preventDefault();
if (quesfield.value == "")
{
labelnques.innerHTML = 'Question field cannot be empty!';
labelnquestags.innerHTML = "";
probchk = true;
return;
}
if (tagsfield.value == "")
{
labelnquestags.innerHTML = 'Please enter (some) relevant tags...';
labelnques.innerHTML = "";
probchk = true;
if (quesfield.value.length > 500)
{
labelnques.innerHTML = 'Question too long (should be 500 characters or less)';
probchk = true;
}
return;
}
}
if (quesfield.value.length > 500)
{
event.preventDefault();
labelnques.innerHTML = 'Question too long (should be 500 characters or less)';
probchk = true;
return;
}
}
***question controller file***
# GET /questions/1
# GET /questions/1.xml
def show
#question = Question.find(params[:id])
if !session[:user_id].nil?
##owner = Document.is_owner(params[:id],session[:user_id])
#fav_count = FavouriteQuestion.count(:all,:conditions=>["question_id = ? AND profile_id = ?",#question.id,session[:user_id]])
if FavouriteQuestion.count(:all,:conditions=>["question_id = ? AND profile_id = ?",#question.id,session[:user_id]]) > 0
#fav_status = 1
else
#fav_status = 0
end
else
#owner = Document.is_owner(params[:id],nil)
#fav_status = 0
end
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #question }
end
end
# GET /questions/new
# GET /questions/new.xml
def new
#question = Question.new
if !session[:user_id].nil?
#question.profile_id = session[:user_id]
end
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #question }
end
end
It appears as if you are doing a, ruby on rails form with javascript validations. While you can do that, I would recommend starting with a basic MVC structure. I highly recommend running through a some basics that will orient you to this. http://guides.rails.info/ is a great place to start. I wish that it had been there when I got started, it would have saved me a great deal of pain :)
The you will want to move your validations into the model.
in app/models/question.rb
class Question < ActiveRecord::Base
validates_presence_of :question
end
more baked in validation options here.
then you want to have a controller to respond to your create events. in app/controller/question_controller.rb:
class QuestionsController < ApplicationController
def new
#question = Question.new
end
def create
#question = Question.new(params[:question])
if #question.save
flash[:confirm] = "You have asked a question"
redirect_to questions_path
else
flash[:error] = #question.errors.full_messages.join(",")
render :action => :new
end
end
end
And then your config/routes.rb
map.resources :questions
Your form should look similar to what you have:
<%= flash[:error] %>
<% form_for(#question) do |f| %>
<%= f.text_field :content ...
<% end %>
the flash is crude, I haven't used it in a while. I use the message_block plugin. You can also read more about how the flash works here
There are plugins to shorten some of this, but I recommend cutting your teeth my doing some of this first. It helps you get oriented. Best of luck!
Related
I'm following as closely as I can to set up simple filtering on a players model using http://filterrific.clearcove.ca/pages/action_view_api.html as an example. However, I keep getting the syntax error below, clearly I'm missing something here!
Error
syntax error, unexpected '<', expecting ')'
</div>
^
/home/jack/Itorix/app/views/players/_list.html.erb:10: unknown regexp options - th
Players Controller
def index
#filterrific = initialize_filterrific(
Player,
params[:filterrific]
) || return
#players = #filterrific.find.page(params[:page])
respond_to do |format|
format.html
format.js
end
end
Players Model
class Player < ApplicationRecord
filterrific(
default_filter_params: { sorted_by: 'tornid' },
available_filters: [
:sorted_by,
])
scope :sorted_by, ->(sort_option) {
# extract the sort direction from the param value.
direction = /desc$/.match?(sort_option) ? "desc" : "asc"
case sort_option.to_s
when /^tornid/
# Simple sort on the created_at column.
# Make sure to include the table name to avoid ambiguous column names.
# Joining on other tables is quite common in Filterrific, and almost
# every ActiveRecord table has a 'created_at' column.
order("players.tornid #{direction}")
else
raise(ArgumentError, "Invalid sort option: #{sort_option.inspect}")
end
}
end
Index.html.erb
<p id="notice"><%= notice %></p>
<h1>Players</h1>
<% js = escape_javascript(
render(partial: 'players/list', locals: { players: #players })
) %>
$("#filterrific_results").html("<%= js %>");
<%= form_for_filterrific #filterrific do |f| %>
<div>
Sorted by
<%= f.select(:sorted_by, #filterrific.select_options[:sorted_by]) %>
</div>
<div>
<%= link_to(
'Reset filters',
reset_filterrific_url,
) %>
</div>
<%# add an automated spinner to your form when the list is refreshed %>
<%= render_filterrific_spinner %>
<% end %>
<%= render(
partial: 'players/list',
locals: { players: #players }
) %>
<%= link_to "New Player", new_player_path %>
_list.html.erb
<%# app/views/players/_list.html.erb %>
<div id="filterrific_results">
<div>
<%= page_entries_info players # provided by will_paginate %>
</div>
<table>
<tr>
<th><%= filterrific_sorting_link(#filterrific, :tornid) %></th>
</tr>
<% players.each do |player| %>
<tr>
<td><%= player.tornid %></td>
</tr>
<% end %>
</table>
</div>
<%= will_paginate players # provided by will_paginate %>
Just came across this issue and solved it by removing the inline comments in the _list file. Remove the # provided by will_paginate from both page_entries_info and will_paginate and the syntax errors go away.
I'm working on a RSS reader and I have to check every x time if a new article is arrived. So I create a function for that in javascript who goes to a controller, then a service, back controller and finish with a js.erb view.
My first issue is that I have an encoding problem on the js.erb file.
My second issue is that even when I don't have data I can't stop the function before goes to the view file. The js.erb then I got a error because the data is nil.
My javascript function :
var actu = setInterval(myTimer, 20000);
function myTimer() {
$.ajax({
url: '/fluxes/actu',
method: 'GET',
});
}
My controller action:
def actu
#fluxes = Flux.all
#new_hash_article = Actualisation.new(#fluxes).call
if #new_hash_article.length >= 1
#new_hash_article.each do |key, value|
#flux = key
#article = value
respond_to do |format|
format.js
end
end
end
end
My service:
require 'rubygems'
require 'simple-rss'
require 'open-uri'
class Actualisation
def initialize(fluxes)
#fluxes = fluxes
end
def call
new_hash_article = {}
#fluxes.each do |flux|
url = flux.Url
rss = SimpleRSS.parse open(url)
#array_items = []
rss.channel.items.each do |item|
#array_items << item
end
#first = #array_items.first
calculator = 0
flux.articles.each do |article|
if article.Publication == #first.pubDate.to_s
calculator += 1
else
calculator += 0
end
end
if calculator == 0
article = Article.new
article.Title = #first.title
article.Description = #first.description
article.Url = #first.link
article.Publication = #first.pubDate
article.Lu = 0
article.flux_id = flux.id
article.save
new_hash_article[flux] = article
end
end
return new_hash_article
end
end
My view actu.js.erb
jQuery('#flux<%= #flux.id %>').append('<%= j render 'articles/show',
article: #article %>');
I don't if it's usefull but it's my articles/show:
<li id="<%= article.id %>">
<div class="content">
<p><%= article.Title %></p>
<a href="<%= article.Url %>" target="_blank" data="<%= article.id
%>">Voir l'article <i class="fas fa-arrow-right"></i></a>
<div id="switchlu" class="display">
<% if article.Lu == 0 %>
<%= link_to "Afficher comme Lu", articles_marklu_path(id:
article.id), :remote => true %>
<% else %>
<p><i class="fas fa-check"></i>Lu</p>
<%= link_to "Afficher comme non Lu", articles_markpalu_path(id:
article.id), :remote => true %>
<% end %>
</div>
</div>
</li>
The issue :
[1]: https://i.stack.imgur.com/WTZBu.png
Thanks for your time, and your help :)
Hello I have 3 lists on one page that will display and each list has a load more button. I want to be able to click the loadmore button and load 3 items per click.
The problem that I am facing is that when i click the load more button, the second page doesnt show up but on the 2nd click it populates only the last page.
Another is when for instance the button is clicked on completed and then clicking the button on expired creates duplicates of the expired list.
So pretty much the all of the buttons are changing all of the lists eventhough they are not corresponding to them.
I realize that im using url_for which may be the reason im in this problem. perhaps there is a better way to achieve this?
When clicking load more button on the console i get:
www.mywebsite.com/your_essays?page_completed=2".
www.mywebsite.com/your_essays?page_completed=3".
www.mywebsite.com/your_essays?page_expired=2".
This shows what the current page is based on the url, however if i have multiple lists how can i achieve this to make each list separate from each other? is there a better way to do this??
reservations_controler.rb:
def your_essays
user = current_user
#reservations = user.reservations.where("user_id = ?", current_user.id).where("status = ?", true)
#pending
#reservations_pending = user.reservations.where("turned_in = ?", false).where("completed = ?", false).where("due_date >= ?", DateTime.now).order(created_at: :desc).page(params[:page_pending]).per_page(3)
#reservations_pending1 = user.reservations.where("turned_in = ?", false).where("completed = ?", false).where("due_date >= ?", DateTime.now).order(created_at: :desc)
#completed
#reservations_completed = user.reservations.where("turned_in = ?", true).where("completed_doc_updated_at <= due_date", true).order(created_at: :desc).page(params[:page_completed]).per_page(3)
#reservations_completed1 = user.reservations.where("turned_in = ?", true).where("completed_doc_updated_at <= due_date", true).order(created_at: :desc)
#expired
#reservations_expired = user.reservations.where("due_date <= ?", DateTime.now).where("turned_in = ?", false).where("completed = ?", false).order(created_at: :desc).page(params[:page_expired]).per_page(3)
#reservations_expired1 = user.reservations.where("due_date <= ?", DateTime.now).where("turned_in = ?", false).where("completed = ?", false).order(created_at: :desc)
end
my_essays.html.erb:
<div id="content-load-more-completed">
<%= render 'your_essays_completed', reservations_completed: #reservations_completed %>
</div>
<% unless #reservations_completed.current_page == #reservations_completed.total_pages %>
<div id="view-more-completed" class="center" style="min-width:100%;" >
<%= link_to('View More', url_for(page_completed: #reservations_completed.current_page + 1), remote: true, class: 'btn btn-back', style: 'min-width:100%;') %>
</div>
<% end %>
<div id="content-load-more-expired">
<%= render 'your_essays_expired', reservations_expired: #reservations_expired %>
</div>
<% unless #reservations_expired.current_page == #reservations_expired.total_pages %>
<div id="view-more-expired" class="center" style="min-width:100%;" >
<%= link_to('View More', url_for(page_expired: #reservations_expired.current_page + 1), remote: true, class: 'btn btn-back', style: 'min-width:100%;') %>
</div>
<% end %>
my_essays.js.erb:
$('#view-more-completed').click(function (event) {
$('#content-load-more-completed').append("<%=j render 'your_essays_completed', reservations_completed: #reservations_completed, format: 'html' %>");
});
<% if #reservations_completed.current_page == #reservations_completed.total_pages %>
$('#view-more-completed').remove();
<% else %>
$('#view-more-completed a').attr('href', '<%= url_for(page_completed: #reservations_completed.current_page + 1) %>');
<% end %>
$('#view-more-expired').click(function (event) {
$('#content-load-more-expired').append("<%=j render 'your_essays_expired', reservations_expired: #reservations_expired, format: 'html' %>");
});
<% if #reservations_expired.current_page == #reservations_expired.total_pages %>
$('#view-more-expired').remove();
<% else %>
$('#view-more-expired a').attr('href', '<%= url_for(page_expired: #reservations_expired.current_page + 1) %>');
<% end %>
partials for _your_essays_completed.html.erb and _your_essays_expired.html.erb:
<% reservations_completed.each do |reservation| %>
<!-- content -->
<% end %>
<% reservations_expired.each do |reservation| %>
<!-- content -->
<% end %>
I have a rails app and when user clicks to login button on header a bootstrap popup modal opens with a form, asks for user email and password. When user types and presses enter, I use window.location.reload(); and the button login turns in to a button with a text says "Welcome <%= current_user.name %>"
What I want to do is, instead of using window location reload, can I update this dynamically?
Here is my sessions#create action
def create
user = User.find_by(email: params[:session][:email].downcase)
respond_to do |format|
if user && user.authenticate(params[:session][:password])
if user.activated?
log_in user
params[:session][:remember_me] == '1' ? remember(user) : forget(user)
format.html { redirect_back_or user }
flash[:notice] = t('flash.sessions.create.success.html')
format.js #here I should do smth
else
format.html { redirect_to root_url }
format.json { render json: {email:['Account not activated. Check your email for the activation link.']} , status: :unprocessable_entity}
format.js { render json: {email:['Account not activated. Check your email for the activation link.']}, status: :unprocessable_entity }
end
then the create.js.erb
// close modal
$('#login-dialog').fadeToggle();
// clear form input elements
// todo/note: handle textarea, select, etc
$('form input[type="text"]').val('');
//Clear previous errors
$('.form-group.has-error').each(function(){
$('.help-block').html('');
$('.form-group').removeClass('has-error');
});
window.location.reload(); #here I am reloading the page then I can see login button disappears and new button saying Welcome Billy appears.
So how can I do that without reloading the window.
Thank you
EDIT
The thing is, I have also signup modal which user can click to open and these modal codes are in header.html.erb, when I render the page as you suggested it gives an error for sign up form;
<% modal ||= false %>
<% remote = modal ? true : false %>
<%= form_for(#user, remote: modal, :html => {role: :form, 'data-model' => 'user'}) do |f| %>
<div class="form-group">
<%= f.label :name, t('header.nameSurname') %>
<span class="help"></span>
<%= f.text_field :name, class: 'form-control' %>
<span class="help-block"></span>
</div>
<div class="form-group">
<%= f.label :username, t('header.username') %>
<span class="help"></span>
<%= f.text_field :username, class: 'form-control' %>
<span class="help-block"></span>
</div>
....
because of #user variable, if I change it to User.new is it ok?, would it create problem?.
I also have 3 different header partials. I normally render them in application.html.erb as;
<div id="render_main">
<% if #header_main %>
<%= render 'layouts/header_main' %> <!--Header comes here-->
<% elsif #header_listing %>
<%= render 'layouts/header_listing' %> <!--Header comes here-->
<% else %>
<%= render 'layouts/header' %>
<% end %>
</div>
But then in create.js.erb;
// close modal
$('#login-dialog').fadeToggle();
// clear form input elements
// todo/note: handle textarea, select, etc
$('form input[type="text"]').val('');
//Clear previous errors
$('.form-group.has-error').each(function(){
$('.help-block').html('');
$('.form-group').removeClass('has-error');
});
//window.location.reload();
<% if #header_main %>
$('#render_main').html('<%= j render "layouts/header_main"%>')
<% elsif #header_listing %>
$('#render_main').html('<%= j render "layouts/header_listing"%>')
<% else %>
$('#render_main').html('<%= j render "layouts/header"%>')
<% end %>
as I render it can not find #header_main variable I believe, so It does not work as it should be. How can I fix this?.
Main controller;
before_action :show_main_header, only: [:home]
def show_main_header
#header_main = true
end
Considering user login, from main controller home action. But it is probably because I actually run from session#create action. how can I fix it?
EDIT
firstly, thank you Rodrigo,
I have written a function to hold last action;
def location_action_name
if !logged_in?
url = Rails.application.routes.recognize_path(request.referrer)
#last_action = url[:action]
end
end
Then I write to create.js.erb;
<% if (#last_action == "home") %>
$('#render_main').html('<%= j render "layouts/header_main"%>')
<% elsif (#last_action == "listings") %>
$('#render_main').html('<%= j render "layouts/header_listing"%>')
<% else %>
$('#render_main').html('<%= j render "layouts/header"%>')
<% end %>
and worked! in case anyone wonders..
Let's say that you have an partial view for render the header (app/views/shared/_header.html.erb), what you need to do is rerender this partial and replace the header html:
create.js.erb
// window.location.reload();
$('#header-container').html('<%= j render "shared/header"%>')
EDIT:
If the #header_main and #header_listing variables are used to render the header partial, you'll need to instantiate them in your sessions#create action.
To do this, add the show_main_header filter to SessionsController too.
I am using Rails 4.1.1 Why do I have to click twice for jQuery effect to show?
I have been Googling but I cannot find any solutions, not sure if there's something wrong with my jQuery code or....
When I click "Submit" for the first time, the effect didn't appear but the POST action is already called, when I click for the second time, the effect appeared and the POST action is called.
Please check below my create.js.erb, users_controller.rb, new.html.erb
create.js.erb
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
$("form").submit(function( event ) {
var email = $("input#user_email").val();
if (email == "") {
$("h1").text( "Email cannot be empty" ).show().fadeOut( 3000 );
return;
} else if (!isValidEmailAddress(email)) {
$("h1").text( "Email address is not valid" ).show().fadeOut( 3000 );
}else {
$("h1").text( "Correct email address" ).show();
}
event.preventDefault();
});
new.html.erb
<%= form_for #user, remote: true do |f| %>
<p>
<%= f.text_field :email %>
</p>
<p>
<%= f.submit :Submit %>
</p>
<% end %>
<h1></h1>
<% #users.each do |user| %>
<tr>
<li><%= user.email %></li>
</tr>
<% end %>
users_controller.rb
class UsersController < ApplicationController
def new
#users = User.all
#user = User.new
end
def create
#user = User.new(user_params)
respond_to do |format|
format.html { redirect_to '/' }
format.js
end
#user.save
end
private
def user_params
params.require(:user).permit(:email)
end
end
Turbo links might be causing this issue -try disabling turbo links in your app , that has worked for me In the past when I've had a similar problem
You're getting the process wrong. When you submit a remote form in Rails, the app sends an AJAX request to the create action and then evals the received js code (from your create.js.erb). So first time you click the button, nothing happens.
The js view is not the place to handle validations, you should put that somewhere in your assets/javascripts. The js view is a place for updating the html view of the page with the form (e.g. adding records to the list, showing received errors, reseting the form).