rail ajax remote form to update text field upon submission - ruby-on-rails

All I want to do is update a text field on my page with a value when my Rails remote form is submitted.
All the source code be found at github here https://github.com/iamliamnorton/fasdac
The form is on the index page...
Controller code...
def index
#calculator = Calculator.new(params[:calculator])
if #calculator.valid?
respond_to do |format|
format.html { redirect_to calculator_path(:calculator => params[:calculator]), :notice => 'Calculation was successfully completed.' }
format.js
end
else
respond_to do |format|
format.html { redirect_to calculator_path(:calculator => params[:calculator]), :alert => "Calculation was not successfully completed. #{#calculator.errors.full_messages.to_sentence}" }
format.js
end
end
My input form
<%= form_for(#calculator, :url => calculator_path, :remote => true) do |f| %>
...
<% end %>
And the index.js.erb
$("#result").value = "SUCCESS!";
I'm trying to update a input text field with name and id 'result'. I cannot get this working, I've tried many different variants in the index.js.erb but cannot get it working. What am I doing wrong?
It looks like the data is being sent to the controller as I can see in the server console
...
Processing by CalculatorController#index as JS
...
But I can't get the text area to update

index.js.erb
$('#result').val("Success!");

Related

Rails flash message after AJAX success

I have to ask about something that probably no one uses anymore. I want to display flash[:notice] after successfully AJAX action. I'm aware of this and that one and even this gist but none of them fit my example:
#controller code
def new
#registrant = Registrant.new
respond_to do |format|
format.html
if params[:add_patient_to_caregiver]
format.js { render partial: 'add_patient_to_caregiver' }
end
end
end
#view triggered controller#new action via AJAX
<%= link_to 'Add Patient to Caregiver', patient_to_caregiver_path(add_patient_to_caregiver: true, patient_to_caregiver: registrant.id), method: :get, remote: true %>
I want to have something like format.js { render partial: 'add_patient_to_caregiver', flash[:notice] = 'Patient Added' } to display it in a view. I've come up with a workaround:
_add_patient_to_caregiver.js.erb
$("#add-patient").html("<%= escape_javascript(render :partial => 'registrants/add_patient') %>");
$("#flash-messages").after("<div class='alert alert-success'> Patient Added </div>");
And flash message shows up but there are no close button there. Is there any better way to do so? or how to add close button to that message so that the whole page doesn't reload when it is pressed?

.js.erb file available to all other views?

So, in my rails app I ajaxified the error messages on one of my pages. the process was (so everyone understands) first, in my 'edit' link_to I added :remote => true at the end of it thus having it send an ajax request. I then added the line format.js in my respond_to do |format| block. Then, I made an edit.js.erb file with the following line of code $('#error').html("<%= flash[:error] %>"); which basically finds the error div in the current page and replaces the html in that div with the error flash message. This is cool right? No more annoying page refreshes in the event of an error.
Question is, I want to do this for all my edit and destroy pages, but how without making an edit.js.erb and destroy.js.erb file for each view folder? seems pretty simple, and maybe im just missing an obvious answer because I'm exhausted, but I can't figure it out... so... help?????
EDIT!
this is my edit controller
def edit
user = User.find(session[:id])
#table = Table.find(params[:id])
if user.id != #table.created_by
flash[:error] = "ERROR"
respond_to do |format|
format.js {render :template => 'shared/show_error'}
format.html
end
else
flash[:error] = ""
respond_to do |format|
format.js {render :template => 'table/edit', :formats => :html}
format.html
end
end
end
Problem now is, it works fine for showing the errors but if there are no errors it doesnt action render the edit page... In the server window it shows it did, but it doesnt actually show on the screen... Any ideas?
I would suggest you then make a general JS.erb file, something like:
# app/views/shared/show_errors.js.erb
('#error').html("<%= flash[:error] %>");
And then in your controller action, or from another JS.erb file, just type:
render :template => "shared/show_errors"
And voila!
I actually fixed my own problem by accident... I removed the line {render :template => 'table/edit', :formats => :html} from the else block.

Rails: rendering the js.erb template using the controller

I have a rails app trying to incorporate some AJAX where clicking new opens a modal window and a form. I want to be able to display the validation errors if it fails so in my create action, i thought about re-rendering the new.js.erb file. Is this the right approach?
def create
#place = Place.new(params[:place])
if #place.save
redirect_to places_path, :notice => "Successfully created place"
else
render "new.js.erb"
end
end
The result I get is escaped js text in my browser like:
$("#new_grouping").html("<div class=\"modal-header\">\n <a class=\"close\" data- dismiss=\"modal\">×<\/a>\n <h3>Create a new menu section<\/h3>\n<\/div>\n<form accept-charset=\"UTF-8\" action=\"/places/1-mama-s-pizza/groupings\" class=\"simple_form new_grouping\" id=\"new_grouping\" method=\"post\" novalidate=\"novalidate\">
I've tried putting various options into the render block but no luck. Any tips?
The best practice would be to support both, AJAX and Non-AJAX calls, in case the user has javascript turned off for any reason.
def create
#place = Place.new(params[:place])
respond_to do |format|
if #place.save
format.html { redirect_to places_path, :notice => "Successfully created place" }
format.js # renders create.js.erb, which could be used to redirect via javascript
else
format.html { render :action => 'new' }
format.js { render :action => 'new' }
end
end
end
The render :action => 'new' actually renders the template of the controller action new which results to new.html.erb respectively to new.js.erb depending if it's a non-AJAX or an AJAX call.
In new.js.erb goes your ERB/javascript code:
$("#new_grouping").html("<%= escape_javascript(...) %>">
As i know, rendering partial in controller is a bad idea, because then response can be without content-type and some browsers can't understand this. if it is some file attached to action you should write
render :action => "create"
or if you need just render a singe partial then in your action file write
<%= render :partial => "path/to/partial" %>
as i said, then you won't have problems with content-type in response

Rails3 Update Action Problem Nested Resource

I've got an problem with my update action for a nested resource.
In my app, my orders have many invoices.
Creating a new invoice, I correctly end up with the following url:
/orders/11/invoices/new
And when I edit the invoice, again, it's all correct:
/orders/11/invoices/3/edit
This works fine when the save is a success, however if the validation fails, it routes back to:
/invoices/3
I have the following in my invoices controller:
def update
# #order = Order.find(params[:order_id])
# #invoice = #order.invoices.find(params[:id])
#invoice = Invoice.find(params[:id])
respond_to do |format|
if #invoice.update_attributes(params[:invoice])
format.html { redirect_to(order_invoice_path(#invoice.order, #invoice), :notice => 'Invoice was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #invoice.errors, :status => :unprocessable_entity }
end
end
end
def edit
#invoice = Invoice.find(params[:id])
3.times { #invoice.invoice_items.build }
end
I'm assuming I need to edit the #invoice.errors part but I don't know what to change it to?
Any help appreciated. Jx
When updating failed, you use "render" (comparing with the "redirect_to" in the succeeding path), this brings you to invoice editing path by default. You can use "redirect_to" here to keep the URI path you want, but need remembering to preserve the models' states so your users don't need to fill the entire form all over again.
A detail instruction can be found here: How to make a render :edit call show the /edit in the address bar
Yan
in your form you should add your order, like this:
<%= form_for [#order, #invoice] ... do |f| %>
...
<% end %>
And then uncomment this two lines
# #order = Order.find(params[:order_id])
# #invoice = #order.invoices.find(params[:id])
so your form will send its request to POST /orders/XX/invoices/XX

How to stay at same url when validation fails

I'm using Ruby on Rails 2.3.8 and I've got a registration form in which I receive a parameter as follows: /registration/4, which 4 is the id of a user who recommended the user that is about to register in the website.
The problem is that if the validation fails when the user submits the registation (the form renders to the controller users, action create_particular) the site will redirect to /users/create_particular, and therefore I lose the parameter with value 4 that I had before. Besides, I want the user to stay at the same url, which is /registration/4
How can I do that?
Then you should rewrite your create method. You should use redirect_to :back instead of render :action
UPD
def new
#word = Word.new(params[:word])
#word.valid? if params[:word]
end
def create
#word = Word.new(params[:word])
if #word.save
redirect_to #word
else
redirect_to new_word_path(:word => params[:word] )
end
end
Looks quite dirty, but this is just a scratch
UPD 2
This is really not the best solution, but it works
# routes.rb
match 'words/new' => 'words#create', :via => :post, :as => :create_word
# words_controller
def new
#word = Word.new
end
def create
#word = Word.new(params[:word])
respond_to do |format|
if #word.save
format.html { redirect_to(#word, :notice => 'Word was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
# views/words/new.html.erb
<%= form_for(#word, :url => create_word_path) do |f| %>
...
<% end %>
Submit to the current URI (e.g. action=""). When the submission is valid, redirect. POST->Redirect->GET is a good habit.
From the top of my head:
Edit your controller (registrations_controller.rb file). Create method by default contains following piece of code:
if #registration.save
format.html { }
format.xml { }
else
format.html { }
format.xml { }
end
Add redirect_to (:back) between brackets to else format.html{}
Ok I solved the problem by doing the following:
1) I created two routes with the same path, but with different conditions method (one it's post and the other one is set to get)
2) I changed the form in order to post to the POST action defined above
3) I added render => :my_action when the validation fails
So that's pretty much it.
Thanks anyway for all your help.
Hidden field. That user ID param has a name by which you extract it in your controller, right? So just put that value in a hidden field of the same name, then it will survive a round-trip.
For example:
<%= hidden_field_tag :referring_user_id, params[:referring_user_id] %>

Resources