javascript - Send & process .json request (in Rails app) -
i have simple task. user should able enter width , height in form , after click form should generate request(link) following:
/find_area.json?width[]=:width&height[]=:height
app should generate response (area = height * width) , display dynamically on page.
all user actions have saved, should post request.
my questions are:
- how create request (generate simple form_for).
- how calculate area(i mean where:)) , give response.
sorry lack of code , information. glad quick , simple answer.
just small summary need using ajax:-
create model
area
,migrate
table , use inform_for
rails g model area height:integer width:integer
run rake db:migrate
//view part <%= form_for(@area,:url=>"areas/find_area",:remote=>true) |f |%> <%= f.text_field :width ,:placeholder=>"enter width",:required=>"true"%> <%= f.text_field :height ,:placeholder=>"enter height",:required=>"true"%>
<button type="submit" data-remote="true"> calculate area</button>
<%end%>add routes in routes.rb handle posting form after submit using ajax
match '/find_area', :to => 'areas#find_area'
in controller method,get values params , calculate area
//inside areas_controller.rb, def find_area width,height=params[:width],params[:height] @area=width*height respond_to |format| if @area format.js else format.js { render :json => @area.errors.full_messages.join(' '), :status => 400 } end end end
render js.erb show pop /text area hide form using css
inside find_area.js.erb
##using hidden div present on page $("#show_area").html("the area <%= @area%>").show();
Comments
Post a Comment