public
Created

Ajax call to update text field

  • Download Gist
_fields.html.erb
HTML+ERB
1 2 3 4 5 6 7 8 9 10
<fieldset>
<div>
<%= f.label :invoice_id %><br/>
<%= f.select(:invoice_id, current_user.outstanding_invoices_collection) %>
</div>
<div>
<%= f.label :amount %><br/>
<%= f.text_field :amount %>
</div>
</fieldset>
application.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
$(function() {
 
$("#payment_invoice_id").change(function() {
// Your the url to your controller action here
$.ajax({
url: 'http://localhost:3000/payments/get_amount',
data: 'invoice_id=' + this.value,
dataType: 'script'
})
});
});
get_amount.js.erb
HTML+ERB
1
$('#payment_amount').val('<%= @amount %>');
payments_controller.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
class PaymentsController < ApplicationController
before_filter :authenticate
before_filter :authorized_user, :only => [:show, :edit, :update, :destroy]
before_filter :check_for_parent, :only => :new
 
def index
result = current_user.payments.search(params[:query], params[:invoice_id]).order(sort_column + " " + sort_direction)
@payments = paginate(result)
@title = "Payments (#{@payments.count} of #{current_user.payments.count})"
end
 
def show
@title = payment_with_number
end
 
def new
@payment = Payment.new(:invoice_id => params[:invoice_id])
# @payment.amount = @payment.invoice.balance.abs if @payment.invoice.present?
@title = "New payment"
end
 
def edit
@title = payment_with_number
end
 
def create
invoice = current_user.invoices.find(params[:payment][:invoice_id])
@payment = invoice.payments.build(params[:payment])
@payment.set_number_for(current_user)
if @payment.save
flash[:success] = "#{payment_with_number} created."
redirect_to payments_path
else
render :action => "new"
end
end
def get_amount
invoice = Invoice.find(params[:invoice_id])
@amount = invoice.balance
end
 
private
 
def authorized_user
@payment = Payment.find(params[:id])
redirect_to root_path unless current_user?(@payment.invoice.project.person.user)
end
def check_for_parent
redirect_to :back, :notice => "There are no payable Invoices." unless current_user.outstanding_invoices.any?
end
 
def payment_with_number
"Payment ##{formatted_number(@payment.number)}"
end
 
end
routes.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Billings::Application.routes.draw do
 
resources :payments do
collection do
get :get_amount
end
end
 
resources :users, :people, :projects, :invoices, :preferences, :payments, :organisations
resources :sessions, :only => [:new, :create, :destroy]
match 'signup', :to => 'users#new'
match 'signin', :to => 'sessions#new'
match 'signout', :to => 'sessions#destroy'
match '/contact', :to => 'pages#contact'
match '/about', :to => 'pages#about'
 
root :to => 'pages#home'
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.