i had a index page with url as www.exa,com/users/jude.In that page i want to submit a from which appears from popup dialog.The action of the popup is going to send_message,Whenever i submits, via ajax the data gets stored but not the page gets reflected.
My controller
def send_message
#message = current_user.messages.build(params[:message])
#message.receiver_id = #user.id
respond_to do |format|
if #message.save
format.html {redirect_to user_url(current_user)}
format.js
end
end
end
View file
%div.jqmWindow#dialog
%div.dialog_content
-form_for Message.new,:url=>'users_message_path',:remote=>true do |f|
=hidden_field_tag :id,#user.login
=f.text_area 'content',:rows => 10, :cols => 25
=f.submit 'Send'
My js.erb
$('#dialog').html("hello")
Problem is ajax is requestuing the action /users/send_message and not /users/jude
Whenever we use haml as a markup, then we have all the files should have .html.haml naming conventions, since views with the .html.haml extension will automatically use Haml.
Now in format.js file we can our updated or inserted data to show
$('#dialog').html('<%= escape_javascript "You have successfully sent your message to #{#message.receiver_id.login}"%>')
Now the data gets inserted via ajax calls
Related
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?
I have my jquery ajax success as
success: function(data) {
$('#someId').html(data);
}
I have a partial file in the name of _information.html.erb
How do i render my ajax success response to rails partial view(information).
Most of the resources showing something like this
$('#holderDiv').empty().append('<ul> <%= j render #comments %> </li>')
But i didn't feel comfortable with it. Any other way to solve it.
UPDATE
Here's some more info in response to your comments.
First please read this Rails Guide on Javascript for more info.
update.js.erb is your view. Instead of having an update.html.erb file for your view, the respond_to block with format.js in your controller will send update.js.erb (formatted as javascript code) back to your jquery function.
update.js.erb could contain pure javascript. However it is processed by the server before being converted to javascript, so you can embed any ruby code you want. That ruby code gets converted into javascript.
If you use chrome developer tools, you can look in the "network" tab after your jquery call runs. You'll see a new entry appear for the AJAX call you just made. If you click on the entry, you'll see the javascript that was returned.
I've updated the update.js.erb file below slightly to show how you can put regular javascript code in the .js.erb file. The first line is javascript. The second line is ruby code which the server converts into javascript. So by the time that it gets to your browser, the entire update.js.erb file has been converted into javascript.
Hope that helps...
Original Answer Below:
Option 1:
Assuming that your jQuery success function is tied to the successful completion of a controller action (I'll use the edit action for my example), you would create a view called update.js.erb which will be called after a successful edit.
Controller:
if #user.update_attributes(params[:user])
respond_to do |format|
format.html { redirect_to #user, notice: "Successfully updated user." }
format.js
end
else
# ...
end
Because this is being called from javascript and you have format.js in the respond_to block, update.js.erb will automatically be called.
update.js.erb:
console.log('see... this is a regular javascript call.');
<%= render partial: 'information', format: 'js' %>
Option 2
The snippet you included:
$('#holderDiv').empty().append('<ul> <%= j render #comments %> </li>')
will only work in a js.erb file, where embedded ruby code is first processed then converted into javascript code. That would work in a situation such as:
Controller:
def create
user = User.new(params[:user])
respond_to do |format|
if #user.save
#comments = 'some comments to display!'
format.js
else
# ...
end
end
end
create.js.erb:
$('#holderDiv').empty().append('<%= j render #comments %>')
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
I'm wanting to add some AJAX functionality to my Rails app, but have no idea where to start.
Here is the method that adds an item to an order:
def add_item_to_order
if session[:order_id].nil?
#order = Order.new #Don't create an order until there is an item to be added to it.
#order.account_id = session[:user_id]
else
#order = Order.find(session[:order_id])
end
item = Item.find(params[:id])
o_item = OrderItem.new
o_item.item_id = item.id
#order.order_items << o_item
#order.total += item.sale_price
#order.save
session[:order_id] = #order.id
redirect_to order_home_path
end
This is run when the user clicks:
<%= link_to item.name, add_item_to_order_path(item.id), :class => "fixed medium green button"%>
Can anyone give me any tips on how to get started, so the the item is added to the order via AJAX?
Check on how to render javascript. In normal requests one would redirect to some action or render some view etc, for a XHR (XmlHttpRequest) you can render javascript through a server-sided js template that would be rendered. You will have to use the LegacyPrototypeHelpers provided for Rails-3 as the original helpers were only officially available for Rails-2.
A better approach(unobtrusive as Rails 3 prefers) will be to just send some data from the server. In the following example you have above I guess if you send item.id via a JSON object or some other format and then read it in the success callback of the place from where you made the XMLHttpRequest, then after getting the item.id you could create the HTML that the link_to creates and then append it to the DOM.
Great tutorial, did this myself: http://ruby.railstutorial.org/ruby-on-rails-tutorial-book Chapter 12 has some stuff on Ajax.
Important part is to set your link_to paramater data-remote to true:
<%= link_to item.name, add_item_to_order_path(item.id),
:class => "fixed medium green button" data-remote="true" method="post"%>
and in your controller you add
def add_item_to_order
# other stuff
# at the bottom:
respond_to do |format|
format.html { redirect_to order_home_path }
format.js
end
end
Then you'll need a .js.erb file to handle the format.js repsonse:
$("your_form").update("<%= escape_javascript(render('partial_page')) %>")
and a partial page file to hold the new data..
So.. I have this in the action called when someone clicks the archive button
respond_to do |format|
format.js do
render :update do |page|
page << "alert('You have reached your archive object limit. You have #{remaining} remaining archived objects.');"
end
end
end
But instead of alerting, it just gets rid of the entire page and shows a JavaScript try / catch with that alert message. How do I just do an alert without rendering anything?
Add
:layout => false
in render
Needed to change form_for to form_remote_for to enable ajax
If it's an AJAX call, you may do something like this in your action:
render :text => "<script type='text/javascript'>alert('bla');</script>"