Search, Sort with AJAX - ajax

I've reproduced the code from RailsCasts episode 240. I have no idea why with this code the Ajax requests don't work. The search function works with the normal method (reload page) sadly not through Ajax. The sort function works not at all.
I've included following JavaScript libraries:
application.js
jQuery JavaScript Library v1.6.2
jQuery UI 1.8.15
jQuery.rails.js
jQuery TinySort v1.1.0
If you need more information please let me know. I hope really you can help me to solve the problems.
users_controller.rb
def index
#users = User.search(params[:search]).order(sort_column + " " + sort_direction)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "lastname"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
index.html.erb
<h1>Listing users</h1>
<%= form_tag users_path, :method => 'get', :id => "users_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="users">
<%= render 'users' %>
</div>
<% end %>
_users.html.erb
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<table class="pretty">
<tr>
<th><%= sortable "Last name" %></th>
<th><%= sortable "First name" %></th>
</tr>
<% for user in #users %>
<tr>
<td><%= user.lastname %></td>
<td><%= user.firstname %></td>
</tr>
<% end %>
</table>
index.js.erb
$("#users").html("<%= escape_javascript(render("users")) %>");
users_helper.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
application.js
$(function() {
$("#users th a").live("click", function() {
$.getScript(this.href);
return false;
});
$("#users_search input").keyup(function() {
$.get($("#users_search").attr("action"), $("#users_search").serialize(), null, "script");
return false;
});
});
Thank you for your help!

For the above code to work, you have to delete the following lines of code.
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
Now it works. :-)

Related

adding event functionality to my redmine calendar using bitnami stack

I want to add, update and delete event on my redmine calendar(almost similar to a google calendar).I have installed redmine on a Bitnami stack. But I'm not able to understand the code structure as I do not have proper documentation. Is there anyone who can help me on this.
The below listed code is my calendar controller .
class CalendarsController < ApplicationController
menu_item :calendar
before_action :find_optional_project
rescue_from Query::StatementInvalid, :with => :query_statement_invalid
helper :issues
helper :projects
helper :queries
include QueriesHelper
def show
if params[:year] and params[:year].to_i > 1900
#year = params[:year].to_i
if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
#month = params[:month].to_i
end
end
#year ||= User.current.today.year
#month ||= User.current.today.month
#calendar = Redmine::Helpers::Calendar.new(Date.civil(#year, #month, 1), current_language, :month)
retrieve_query
#query.group_by = nil
#query.sort_criteria = nil
if #query.valid?
events = []
events += #query.issues(:include => [:tracker, :assigned_to, :priority],
:conditions => ["((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", #calendar.startdt, #calendar.enddt, #calendar.startdt, #calendar.enddt]
)
events += #query.versions(:conditions => ["effective_date BETWEEN ? AND ?", #calendar.startdt, #calendar.enddt])
#calendar.events = events
end
render :action => 'show', :layout => false if request.xhr?
end
end
The below is the calender_helper.rb
module CalendarsHelper
def link_to_previous_month(year, month, options={})
target_year, target_month = if month == 1
[year - 1, 12]
else
[year, month - 1]
end
name = if target_month == 12
"#{month_name(target_month)} #{target_year}"
else
"#{month_name(target_month)}"
end
# \xc2\xab(utf-8) = «
link_to_month(("\xc2\xab " + name), target_year, target_month, options)
end
def link_to_next_month(year, month, options={})
target_year, target_month = if month == 12
[year + 1, 1]
else
[year, month + 1]
end
name = if target_month == 1
"#{month_name(target_month)} #{target_year}"
else
"#{month_name(target_month)}"
end
# \xc2\xbb(utf-8) = »
link_to_month((name + " \xc2\xbb"), target_year, target_month, options)
end
def link_to_month(link_name, year, month, options={})
link_to(link_name, {:params => request.query_parameters.merge(:year => year, :month => month)}, options)
end
end
Below is the view ,show.html.erb
<h2><%= #query.new_record? ? l(:label_calendar) : #query.name %></h2>
<%= form_tag({:controller => 'calendars', :action => 'show', :project_id => #project},
:method => :get, :id => 'query_form') do %>
<%= hidden_field_tag 'set_filter', '1' %>
<fieldset id="filters" class="collapsible <%= #query.new_record? ? "" : "collapsed" %>">
<legend onclick="toggleFieldset(this);"><%= l(:label_filter_plural) %></legend>
<div style="<%= #query.new_record? ? "" : "display: none;" %>">
<%= render :partial => 'queries/filters', :locals => {:query => #query} %>
</div>
</fieldset>
<p style="float:right;">
<%= link_to_previous_month(#year, #month, :accesskey => accesskey(:previous)) %> | <%= link_to_next_month(#year, #month, :accesskey => accesskey(:next)) %>
</p>
<p class="buttons">
<%= label_tag('month', l(:label_month)) %>
<%= select_month(#month, :prefix => "month", :discard_type => true) %>
<%= label_tag('year', l(:label_year)) %>
<%= select_year(#year, :prefix => "year", :discard_type => true) %>
<%= link_to_function l(:button_apply), '$("#query_form").submit()', :class => 'icon icon-checked' %>
<%= link_to l(:button_clear), { :project_id => #project, :set_filter => 1 }, :class => 'icon icon-reload' %>
</p>
<% end %>
<%= error_messages_for 'query' %>
<% if #query.valid? %>
<%= render :partial => 'common/calendar', :locals => {:calendar => #calendar} %>
<%= call_hook(:view_calendars_show_bottom, :year => #year, :month => #month, :project => #project, :query => #query) %>
<p class="legend cal">
<span class="starting"><%= l(:text_tip_issue_begin_day) %></span>
<span class="ending"><%= l(:text_tip_issue_end_day) %></span>
<span class="starting ending"><%= l(:text_tip_issue_begin_end_day) %></span>
</p>
<% end %>
<% content_for :sidebar do %>
<%= render :partial => 'issues/sidebar' %>
<% end %>
<% html_title(l(:label_calendar)) -%>
This is the only code related to calendar in routes.rb
get '/projects/:project_id/issues/calendar', :to => 'calendars#show', :as => 'project_calendar'
get '/issues/calendar', :to => 'calendars#show'
In this controller you have only show action (HTTP GET). If you want update and delete you are supposed to add methods and logic for them gere. You will also need routes in config/routes.rb.
I would also recommend you to take a look into other controllers since this one looks more like a renderer of the calendar and nothing more. I don't see create action as well (HTTP POST) which means you create the entity somewhere else and update and delete are supposed to be there as well (if they are not defined already).

Routing error in activerecord reputation gem in rails 4

Hello I'm new to rails 4
I am working on project where we can post and rate it. I have used activerecord reputation gem. I have been following the http://railscasts.com/episodes/364-active-record-reputation-system video.
I am stuck at the routing point. When I click on upvote or downvote it shows me error.
my routes.rb file has
resources :posts do
resources :comments, :only => [:create]
member { post :vote }
end
get "posts/create"
get "posts/destroy"
get "posts/new"
get "posts/index"
get "posts/show"
get "posts/edit"
get "posts/update"
_post.html.erb
<h4 class="timeline-title"><%= link_to_unless_current post.title, post %></h4>
<p> Created : <%= post.created_at.strftime("%d/%m/%Y") %> by <%= post.postedby %>
</p>
<% if current_cubestudent.email == post.postedby %>
<p><%= link_to 'Edit', edit_post_path(#post) %>
<%= link_to 'Destroy', posts_path, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
<%= simple_format post.body , :class => "timeline-body"%>
<%= pluralize post.reputation_for( :votes).to_i, "vote" %>
<% if current_cubestudent && !current_cubestudent.voted_for?(post) %>
<%= link_to "up", vote_post_path(post, type: "up"), method: "post" %>
<%= link_to "down", vote_post_path(post, type: "down"), method: "post" %>
<% end %>
my post#show is
<%= stylesheet_link_tag "application",:media =>"screen" %>
<p id="notice"><%= notice %></p>
<p id="alert"><%= alert %></p>
<%= render :partial => #post %>
<%= link_to 'Back', posts_path %>
<h2 id="timeline">Comments</h2>
<div>
<%= render :partial => #post.comments %>
</div>
<div class="container">
<%= form_for [#post, Comment.new] do |f| %>
<div style="padding-bottom:0">
<%= f.text_area :body , :placeholder => "Write your comment"%>
<%= f.submit "Add comment", :class => "btn btn-info" %>
</div>
<% end %>
</div>
posts controller is
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def create
#post = Post.new(post_params)
#post.postedby = current_cubestudent.email
#post.postedbyid = current_cubestudent.id
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: #post }
else
format.html { render action: 'new' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
def new
#post = Post.new
end
def index
#posts = Post.find_with_reputation(:votes, :all, order: "votes desc")
end
def show
#post = Post.find(params[:id])
end
def edit
end
def update
respond_to do |format|
if #post.update(post_params)
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def vote
value = params[:type] == "up" ? 1 : -1
#post = Post.find(params[:id])
#post.add_or_update_evaluation(:votes, value, current_cubestudent)
redirect_to :back, notice: "Thank you for voting"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :body, :subject)
end
end
after rake routes | grep post
C:\Sites\project>rake routes | grep post
post_comments POST /posts/:post_id/comments(.:form comments#create
vote_post POST /posts/:id/vote(.:format) posts#vote
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
posts_create GET /posts/create(.:format) posts#create
posts_destroy GET /posts/destroy(.:format) posts#destroy
posts_new GET /posts/new(.:format) posts#new
posts_index GET /posts/index(.:format) posts#index
posts_show GET /posts/show(.:format) posts#show
posts_edit GET /posts/edit(.:format) posts#edit
posts_update GET /posts/update(.:format) posts#update
Can someone help me on it....??
Your main problem is in this code
<%= link_to "up", vote_post_path(post, type: "up"), method: "post" %>
you would like to send "post" request but in fact you send default ("get") request.
I can suppose that link_to accepts only symbols for method (you pass string). So try this
<%= link_to "up", vote_post_path(post, type: "up"), method: :post %>
Another source of the problem can be wrong routes. If code above does not help you run in console rake routes | grep post and add output to the question.

Hw do i render a partial in rails 3.0 using ajax, on radio button select?

I try a bit of ajax first time but did not get success, i want to render a partial on radio button select using ajax, here is my code :
My script.js:
$(document).ready(function(){
$.ajax({
url : "/income_vouchers/income_voucher_partial?$('form input[type=radio]:checked').val()="+$('form input[type=radio]:checked').val(),
type: "GET",
data: {
type: $('form input[type=radio]:checked').val()
}
});
});
income_voucher.js.erb
$("#payment_mode").append('
<% if params[:type]== 'cheque' %>
<%= escape_javascript render :partial => "cheque" %>
<% elsif params[:type]=='card' %>
<%= escape_javascript render :partial => "card" %>
<% elsif params[:type]=='ibank'%>
<%= escape_javascript render :partial => "ibank" %>
<% else params[:type] == 'cash' %>
<% end %>
');
My from:
<script type="text/javascript" src="/javascripts/voucher.js"></script>
<%= form_for(#income_voucher) do |f| %>
<%= render 'shared/form_error', :object => #income_voucher %>
<div >
<%= radio_button_tag :transaction_type,'cash', :checked => true %>
<%= f.label :transaction_type, "Cash", :value => "cash" %>
<%= radio_button_tag :transaction_type,'cheque' %>
<%= f.label :transaction_type, "Cheque", :value => "cheque" %>
<%= radio_button_tag :transaction_type,'card'%>
<%= f.label :transaction_type, "Card", :value => "card" %>
<%= radio_button_tag :transaction_type,'ibank'%>
<%= f.label :transaction_type, "Internet Banking", :value => "ibank" %>
</div>
<div id = "payment_mode">
<% if params[:type]== "cheque" %>
<%= render :partial => "cheque", :f => f %>
<% elsif params[:type]=='card' %>
<%= render :partial => "card", :f => f %>
<% elseif params[:type] == 'ibank'%>
<%= render :partial => "ibank", :f => f %>
<% else params[:type] == 'cash' %>
<% end %>
</div>
<%= f.submit %>
<% end %>
and here is my controller method:
class IncomeVouchersController < ApplicationController
def new
#income_voucher = IncomeVoucher.new
#invoices = current_company.invoices
#income_voucher.build_payment_mode
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #income_voucher }
end
end
def create
#income_voucher = IncomeVoucher.new(params[:income_voucher])
transaction_type = params[:transaction_type]
payment_mode = nil
if transaction_type == 'cheque'
payment = ChequePayment.new(params[:cheque_payment])
payment.amount = #income_voucher.amount
elsif transaction_type == 'card'
payment = CardPayment.new(params[:card_payment])
payment.amount = #income_voucher.amount
elsif transaction_type == 'ibank'
payment = InternetBankingPayment.new(params[:internet_banking_payment])
payment.amount = #income_voucher.amount
else
payment = CashPayment.new
payment.amount = #income_voucher.amount
end
payment_mode = PaymentMode.new
payment_mode.transactionable = payment
#income_voucher.payment_mode = payment_mode
respond_to do |format|
if #income_voucher.save
format.html { redirect_to(#income_voucher, :notice => 'Income voucher was successfully created.') }
format.xml { render :xml => #income_voucher, :status => :created, :location => #income_voucher }
else
format.html { render :action => "new" }
format.xml { render :xml => #income_voucher.errors, :status => :unprocessable_entity }
end
end
def income_voucher_partial
#payment_mode = PaymentMode.new(params[:payment_mode])
end
end
i can see my view form but when select a radio button nothing is rende. Any help would be appreciated
First of all: choose the method - or you using remote form, or ajax submit. If your want that user choose radio button AND click submit to render use in .html.erb:
form_for(#income_voucher, :remote => true)
remove javascript ajax and change param name in .js.erb to :transaction_type
If you want that user choosse radio button and immidiately render move javascript ajax to radio button change event handler like this
$(your_element).change(function(){
$.ajax(){
url : "/income_vouchers/income_voucher_partial",
data: {
type: $('form input[type=radio]:checked').val()
}
}
});
and remove params setting from directly url - set params in 'data:'
in my js.erb file i did this
$(".gradeU").remove();
$("#abcd").after(
'<%= escape_javascript render :partial => params[:payment] unless params[:payment] == 'cash' %>'
);
and in my script :
$(document).ready(function(){
$("#check").click(function(){
var payment = $('form input[type= radio]:checked').val()
console.debug(payment);
$.ajax({
type: 'GET',
url : "/income_vouchers/income_voucher_partial?payment="+payment,
});
});
});
and i did not render same code in form, thanks

Render current page with new data

Here is my simple ajax code.
The request is made, I get the response but my view does not get rendered with new data. I get a new page with new html that I asked to render instead being rendered inside current page.
controller -
def list
#users = User.find(:all)
end
def show
respond_to do |format|
format.html { render :partial => "ajaxshow" }
format.js
end
end
view -
<% #users.each do |c| %>
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id, :remote => true } %>
<% end %>
partial -
# cat _ajaxshow.html.erb
<div align="left" id="user_ajax">
<table width="1000px">
<tr><th>User ID</th><th>First</th><th>Last</th><th>ID</th><th>Email</th></tr>
</table>
log -
Started GET "/users/show?remote=true&user_id=someuser" for 10.10.10.10 at 2012-04-17 04:01:09 -0400
Processing by UsersController#show as HTML
Parameters: {"remote"=>"true", "user_id"=>"someuser"}
Rendered users/_ajaxshow.html.erb (0.3ms)
Completed 200 OK in 2ms (Views: 1.3ms | ActiveRecord: 0.0ms)
Your link_to will not trigger the ajax call
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id, :remote => true } %>
First change the above code
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id }, { :remote => true, :method => :get } %>
You need to have a .js.erb file for the User controller action which will be called through the format.js call.
In show.js.erb use
$('#some_div_id').html($('<%= render :partial => "ajaxshow" %>'))
Anyhow the purpose of your action seems obscure to me.

how does a button_to in rails request a JSON response?

Im a rails noob, so bear with me.
I have the following in new.html.erb:
<h1>New page</h1>
<%= render 'pages/form' %>
<% if #page != 1 %>
<%= button_to 'New Page', pages_path %>
<%= button_to 'Done!', :action=> 'generate' %>
<% end %>
my controller looks like this
def generate
#presentation = current_presentation
respond_to do |format|
format.json { render json: #presentation.pages}
format.html {render :text => "html"}
end
end
I want the response to be JSON, but the code goes to format.html.
How do I instruct the button_to that my requested response is JSON?
Not sure if just one of them or both, but try :remote => true and data-type:
<%= button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" } %>
Using a path helper to build the path worked for me. eg.
<%= button_to "Create Widgit", widgits_path(format: 'json'), remote: true %>

Resources