<%= submit_to_remote(:category, :url => params[:id].blank? ? {:action => 'create'} : {:action => "update", :id => #category}) do %>
<table>
<tr>
<th>Name</th>
</tr>
<tr>
<td><%= text_field(:category, :name, :size => 20) %></td>
<td><%= submit_tag(params[:id].blank? ? "New": "Edit") %></td>
</tr>
</table>
<% end %>
I want to create new record using Ajax. I got error undefined method submit_to_remote I declared prototype file in layout.
waiting for ans.......
Firstly, it looks like your submit_to_remote is trying to define a form - so use form_for or form_tag.
Secondly submit_to_remote no longer exists in Rails 3. You need the :remote => true option of form_tag, which will let UJS (Unobtrusive JavaScript) step in and make the AJAX happen.
See some docs.
Related
So I have a check_box in rails 5, and I want it to submit instantly whenever it is clicked/unclicked. It should be possible with :onclick, but I'm new to js/jquery/ajax, and haven't had any luck searching.
I have this:
<%= form_for #client, :url => url_for(:controller => 'client_admin', :action => 'clientadminpageupdate') do |f| %>
<%= f.check_box :visible, :id => "checkbox" %>
<%= f.submit 'Save' %>
What I want to this is submit the form instantly by adding an
:onclick => something-that-submits-the-form-instantly
How do I go about it?
If you just want to use it as a form submission you can use the following:
:onclick => "this.form.submit()"
I am a relative novice with rails and I am trying to use the filterrific gem for some filtering. Basically I have the index page that shows a list of vendors and I want to be able to use the filtering to actively filter/sort the records. I was able to get through the tutorial and got through all of the errors, but for some reason when you enter data into the forms, nothing happens. It is not refreshing the view at all. Any thoughts on what I am doing wrong?
Vendor Model:
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: [
:sorted_by,
:search_query,
:with_vendor_type_id,
:with_created_at_gte
]
)
scope :search_query, lambda { |query|
return nil if query.blank?
terms = query.downcase.split(/\s+/)
terms = terms.map { |e|
(e.gsub('*', '%') + '%').gsub(/%+/, '%')
}
num_or_conds = 2
where(
terms.map { |term|
"(LOWER(vendors.name) LIKE ? OR LOWER(vendors.bio) LIKE ?)"
}.join(' AND '),
*terms.map { |e| [e] * num_or_conds }.flatten
)
}
scope :sorted_by, lambda { |sort_option|
direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
case sort_option.to_s
when /^created_at_/
order("vendors.created_at #{ direction }")
when /^name_/
order("LOWER(vendors.name) #{ direction }, LOWER(students.bio) #{ direction }")
when /^vendor_type_title_/
order("LOWER(vnedor_types.title) #{ direction }").includes(:vendor_type)
else
raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
end
}
scope :with_vendor_type_id, lambda { |vendor_type_ids|
where(with_vendor_type_id: [*vendor_type_ids])
}
scope :created_at_gte, lambda { |reference_time|
where('vendors.created_at >= ?', reference_time)
}
def self.options_for_sorted_by
[
['Name (a-z)', 'name_asc'],
['Registration date (newest first)', 'created_at_desc'],
['Registration date (oldest first)', 'created_at_asc'],
['Type(a-z)', 'vendor_type_id_asc']
]
end
My Vendor Controller
def index
#filterrific = initialize_filterrific(
Vendor,
params[:filterrific],
select_options: {
sorted_by: Vendor.options_for_sorted_by,
with_vendor_type_id: VendorType.options_for_select
},
persistence_id: 'shared_key',
default_filter_params: {},
available_filters: [],
) or return
#vendors = #filterrific.find.page(params[:page])
# Respond to html for initial page load and to js for AJAX filter updates.
respond_to do |format|
format.html
format.js
end
rescue ActiveRecord::RecordNotFound => e
puts "Had to reset filterrific params: #{ e.message }"
redirect_to(reset_filterrific_url(format: :html)) and return
end
My Index View
<h1>Vendors</h1>
<%= form_for_filterrific #filterrific do |f| %>
<div>
Search
<%= f.text_field(
:search_query,
class: 'filterrific-periodically-observed'
) %>
</div>
<div>
Vendor Type
<%= f.select(
:with_vendor_type_id,
#filterrific.select_options[:with_vendor_type_id],
{ include_blank: '- Any -' }
) %>
</div>
<div>
Registered after
<%= f.text_field(:with_created_at_gte, class: 'js-datepicker') %>
</div>
<div>
Sorted by
<%= f.select(:sorted_by, #filterrific.select_options[:sorted_by]) %>
</div>
<div>
<%= link_to(
'Reset filters',
reset_filterrific_url,
) %>
</div>
<% end %>
<%= render(
partial: 'vendors/list',
locals: { vendors: #vendors }
) %>
My Partial
<div id="filterrific_results">
<div>
<%= page_entries_info vendors %>
</div>
<table>
<tr>
<th>Name</th>
<th>User ID</th>
<th>Country</th>
<th>Registered at</th>
</tr>
<% vendors.each do |vendor| %>
<tr>
<td><%= link_to(vendor.name, vendor_path(vendor)) %></td>
<td><%= vendor.user_id %></td>
<td><%= vendor.vendor_type %></td>
<td><%= vendor.created_at %></td>
</tr>
<% end %>
</table>
</div>
<%= will_paginate vendors %>
The JS file
<%# app/views/vendor/index.js.erb %>
<% js = escape_javascript(
render(partial: 'vendors/list', locals: { vendors: #vendors })
) %>
$("#filterrific_results").html("<%= js %>");
I got to the point where the from renders and got past all of the error messages, but its just not actually doing the filtering.
Include //= require filterrific/filterrific-jquery in 'app/assets/javascripts/application.js'
I am developing a ruby on rails app which as vote up and vote down for products. The code is working the only problem I have is I need votes to be submitted via javascript and I have no idea how to begin this.
Heres my routes
resources :products do
member do
post :vote_up
post :vote_down
end
end
heres is my controller file
def vote_up
begin
#product = Product.find(params[:id])
current_user.vote_exclusively_for(#product)
#product.score = #product.plusminus
#product.save
render :nothing => true, :status => 200
rescue ActiveRecord::RecordInvalid
render :nothing =>true, :status => 404
end
end
def vote_down
begin
#product = Product.find(params[:id])
current_user.vote_exclusively_against(#product)
#product.score = #product.plusminus
#product.save
render :nothing => true, :status => 200
rescue ActiveRecord::RecordInvalid
render :nothing =>true, :status => 404
end
end
and here is my view file
<td><%= link_to "Vote up", vote_up_product_path(product), :method=>:post %></td>
<td><%= link_to "Vote down", vote_down_product_path(product), :method=>:post %></td>
javascript includes
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
<td><%= link_to "Vote up", vote_up_product_path(product), :method=>:post, :remote => :true %></td>
Then you can handle the response attaching an event handler to that link:
$(the_link_selector)
.on('ajax:success', function1) // Executed when server answers with successful code
.on('ajax:error', function2) // Executed when server answers with error code
I am creating a statusboard that will show specific details of several servers and need help with updating the view.
Background:
I have the main setup created where I have the following:
A MySQL database that keeps hold of the server information called servers
Using bootstrap to show the content
A ruby script to grab each servers information and updating the database (method called update_all_servers in the application.rb file)
Cronjob that runs the ruby script every minute
What I need help with:
Basically, I need help with the javascript part of my rails app. I am not too sure exactly how too update individual attributes of each server in the table I have. What I am looking for is that the javascript/ajax code will periodically grab the updated values from the database every 30 seconds and update the view without refreshing the page.
In my index.html, you can see that I have placed an id="comments" for the server.rhel_version attribute. I was thinking I could use the $(#comments). to update it. Either in the application.js file or some other efficient/logical method.
Below is all my source code. If you guys could guide me on the approach I should take and possibly provide some sample code, I would really appreciate it!
/views/servers/index.html.erb
<%- model_class = Server.new.class -%>
<div class="page-header">
<h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<!-- <th><%= model_class.human_attribute_name(:id) %></th> -->
<th><%= model_class.human_attribute_name(:hostname) %></th>
<th><%= model_class.human_attribute_name(:port) %></th>
<!-- <th><%= model_class.human_attribute_name(:username) %></th>
<th><%= model_class.human_attribute_name(:password) %></th>
<th><%= model_class.human_attribute_name(:ssh_username) %></th>
<th><%= model_class.human_attribute_name(:ssh_password) %></th>
<th><%= model_class.human_attribute_name(:source_branch) %></th> -->
<th><%= model_class.human_attribute_name(:source_revision) %></th>
<th><%= model_class.human_attribute_name(:release) %></th>
<th><%= model_class.human_attribute_name(:rhel_version) %></th>
<th><%= model_class.human_attribute_name(:gpu_type) %></th>
<th><%= model_class.human_attribute_name(:total_users) %></th>
<th><%= model_class.human_attribute_name(:current_users) %></th>
<th><%= model_class.human_attribute_name(:created_at) %></th>
<th><%=t '.actions', :default => t("helpers.actions") %></th>
</tr>
</thead>
<tbody>
<% #servers.each do |server| %>
<tr>
<!-- <td><%= link_to server.id, server_path(server) %></td> -->
<td><%= server.hostname %></td>
<td><%= server.port %></td>
<!-- <td><%= server.username %></td>
<td><%= server.password %></td>
<td><%= server.ssh_username %></td>
<td><%= server.ssh_password %></td>
<td><%= server.source_branch %></td> -->
<td><%= server.source_revision %></td>
<td><%= server.release %></td>
<td id="comments"><%= server.rhel_version %></td>
<td><%= server.gpu_type %></td>
<td><%= server.total_users %></td>
<td><%= server.current_users %></td>
<td><%=l server.created_at %></td>
<td>
<%= link_to t('.edit', :default => t("helpers.links.edit")),
edit_server_path(server), :class => 'btn btn-mini' %>
<%= link_to t('.destroy', :default => t("helpers.links.destroy")),
server_path(server),
:method => :delete,
:confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')),
:class => 'btn btn-mini btn-danger' %>
</td>
</tr>
<% end %>
</tbody>
</table>
<%= link_to t('.new', :default => t("helpers.links.new")),
new_server_path,
:class => 'btn btn-primary' %>
/controllers/servers_controller.rb
class ServersController < ApplicationController
# GET /servers
# GET /servers.json
def index
#servers = Server.all
update_all_servers
respond_to do |format|
format.html # index.html.erb
format.json { render json: #servers }
end
end
# GET /servers/1
# GET /servers/1.json
def show
#server = Server.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #server }
end
end
# GET /servers/new
# GET /servers/new.json
def new
#server = Server.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #server }
end
end
# GET /servers/1/edit
def edit
#server = Server.find(params[:id])
end
# POST /servers
# POST /servers.json
def create
#server = Server.new(params[:server])
respond_to do |format|
if #server.save
format.html { redirect_to #server, notice: 'Server was successfully created.' }
format.json { render json: #server, status: :created, location: #server }
else
format.html { render action: "new" }
format.json { render json: #server.errors, status: :unprocessable_entity }
end
end
end
# PUT /servers/1
# PUT /servers/1.json
def update
#server = Server.find(params[:id])
respond_to do |format|
if #server.update_attributes(params[:server])
format.html { redirect_to #server, notice: 'Server was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #server.errors, status: :unprocessable_entity }
end
end
end
# DELETE /servers/1
# DELETE /servers/1.json
def destroy
#server = Server.find(params[:id])
#server.destroy
respond_to do |format|
format.html { redirect_to servers_url }
format.json { head :no_content }
end
end
end
/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
Screenshot of view:
You can do all of these with jQuery.ajax and if you search you can easily find related question/answers eg How to fire AJAX request Periodically?
How do i introduce validation before remote_form_for submits?
I have javascript function called validateForm(). I am able to call it before the AJAX request process. I tried to use return false and event.preventDefault. But there seems to be no effect. Here is what my code looks like
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv", :url => {:action => "login", :controller => "site"}, :onsubmit => "validateForm(event)" do |f| %>
User name : <%= f.text_field "uxUserName", :class => "TextBox", :style => "width:100px;" %> *
Password : <%= f.password_field "uxPassword", :class => "TextBox", :style => "width:100px;" %> *
<%= f.submit "Go!", :class => "Button-Simple", :id => "uxSubmitButton" %>
<% end %>
the javascript function is simple as follows
function validateForm(event){
return false;
//event.preventDefault();
}
Try this
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv", :url => {:action => "login", :controller => "site"}, :html => {:id => "uxLoginForm"}, :onsubmit => "return validateForm(event)" do |f| %>
i.e. change
:onsubmit => "validateForm(event)
to
:onsubmit => "return validateForm(event)
EDITED it should be
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv",
:url => {:action => "login", :controller => "site"},
:html => {:id => "uxLoginForm", :onsubmit => "return validateForm(event)"}
do |f|
%>
EDITED AGAIN
WHY don't you use :condition for it? something like following
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv",
:url => {:action => "login", :controller => "site"},
:html => {:id => "uxLoginForm"},
:condition=>"validateForm(event)!=false"
do |f|
%>
I think what you're looking for is something like onSubmit="return validateForm(this)" or thereabouts. Then if the validation returns false (because it failed validation) the form should not submit.
You might want to check LIvevalidation plugin (http://github.com/augustl/live-validations) which you can you to do Ajax with active record validations
And its always good to have non-ajax validations also (even though you use ajax validations) as ajax will not work in javascript disable browser
cheers,
sameera