I found a number of questions and answers regarding updating a partial using Ajax after submitting a form. But my question is ?simpler?, I just want to reload a partial every few seconds and load in the new data. This really can't be hard at all, and I remember doing something similar in Rails 2.3 but I can't find the answer anywhere.
Basically, I have a show.html.erb rendering a partial like so:
<div id="latest_post">
<%= render :partial=>'info/latest', :object=>#user, :as=>:user %>
</div>
The partial file located at app/views/info/_latest
<% post = user.posts.last %>
<h1>Last Post</h1>
<p><%= post.content %></p>
I just want the latest_post div to be updated every 30 seconds. Please help!
Well it turns out the answer is a little complicated:
Step 1: Use Javascript's setInterval function along with jQuery's $.get() function to load a page, say /users/1/posts/latest.
setInterval(function(){
$.get("/users/1/posts/latest.js", function(data){
$("latest_post").html(data);
},
"html")
}, 30000);
Step 2: Create a latest.js.erb and put it in your app/views/posts folder.
Contents of latest.js.erb:
<%= render partial: 'posts/latest', object: #user.posts.last, as: :post %>
Step 3: Create the above partial with whatever you'd like (if you don't need a partial, you can just write the entire contents of the div in the latest.js.erb file.)
Step 4: Add a latest method to your PostsController, that defines #user, etc. for the latest.js.erb to use.
Step 5: Add get '/latest' to your routes.rb
Related
I'm trying to implement some Ajax in my app. A strange behaviour occurs!
It's a daycare application. When you show a specific daycare of a specific date you can add some children.
Originally a list of the children of the database is generated and when you click on one of them the page reload and a new child appears in the attendance list of the daycare. It's working fine, i just wanna add some ajax to be more userfriendly !
When you click on child to add him to the daycare, a daycare_item is created ( join table, an id of the child and the id of the daycare ).
I make the changes to make it ajax ready:
partial for the list
format.js in the daycare_item controller
remote true on the link.
It works, no more reload! But the list is updated only when you click a second time on the children list ( the last child added doesn't appears yet ). The js transaction works and if you refresh manually the page, the missing child appears.
I tried few things and here are my results:
In my partial there are
<% #daycare.daycare_items.each do |c| %>
<li><%= c.child.firstname ></li>
<% end %>
This produce the "lag" effect with one children who is not showing ( until a full refresh )
But if i put a
<%= #daycare.daycare_items.count %>
the code is update in time !
I see nothing strange in the logs.
I'm asking why the .each method make a difference?
A var was stoping a part of the code to be executed, the var wasn't wrong and doesn't generate an error.
The elements involved:
daycare_items controller
def create
#daycare = Daycare.find(params[:daycare_id]) # for Ajax
#daycare_item = DaycareItem.new(params[:daycare_item])
....
end
the create.js.erb
$('#children-list').html(" <%=j render partial: 'daycares/daycare', locals: { daycare: #daycare } %> ");
the view daycares#show
<div id="children-list">
<%= render #daycare %>
</div>
the partial ( a part of ) _daycare.html.erb
<p>counting test:<%= daycare.daycare_items.count %></p>
# here was something like this <%= #waiting.count %> #waiting is define in the daycare controller but not in the daycare_items controller
<p>
<% daycare.daycare_items.each do |dci| %>
<%= dci.enfant.prenom %>
<% end %>
</p>
I'm using Carrierwave to add and upload an image to Amazon S3. this works ok, and once the form is saved I display the image and an x box to remove it.
I would like to use ajax to handle the click event on the 'x' image' on click I would like to remove the image and clear the field on the form so that the input field is once again displayed
The image field is an attribute of the model class i am editing in the form.
Person < ActiveRecord
attr_accessible: image
the partial for this part of my form shows the image if it exists, otherwise the input file_field if it does not exists
<div class="field">
<%= image_tag #pass.background_image_url(:thumb) if #pass.background_image? %>
<%= f.file_field :background_image if #pass.background_image.to_s == '' %>
<%= content_tag :div, '', class: "delete_image_fields" if #pass.background_image? %>
</div>
I have some jquery which i can sccessful hide the image field.
jQuery ->
$('.field .delete_image_fields').click ->
$(this).parent().find('img').hide()
event.preventDefault()
The image field gets hidden no problem
What i would like to happen is
a) clear the input field from the pass object
b) submit the change (remotely)
c) delete the remote image on S3
e) re-display the file_input field for the image so it can re-selected if required
Any help or pointers would be appreciated
UPDATE
I've got this partially working to display corect fields and adjust the input link. but i'm not sure how to actually delete the file from the models attribute
I've updated the partial to the following which dispalsy either the image ro the create file button
<div class="field">
<%= f.label :background_image %><br />
<% if #pass.background_image?%>
<%= image_tag #pass.background_image_url(:thumb) %>
<%= f.file_field :background_image , style: "display:none"%>
<%= content_tag :div, '', class: "delete_image_fields" %>
<% else %>
<%= f.file_field :background_image%>
<% end %>
and updated my jquery to this
$('.field .delete_image_fields').click ->
$(this).parent().find('img').hide()
$(this).hide()
$(this).parent().find('input').val('')
$(this).parent().find('input').show()
event.preventDefault()
To delete the file, you could take advantage of the remove_mounted_field_url carrierwave creates.
From here I see two solutions, either create a new action in your controller that will only remove the file, either use the update action. I like to use as much as possible the original actions(index/new/create ...), so I will use the second solution.
You need to do an AJAX PUT request when clicking on the X box. Here what it could look like :
$('.field .delete_image_fields').click ->
$(this).parent().find('img').hide()
$(this).hide()
$(this).parent().find('input').val('')
$(this).parent().find('input').show()
event.preventDefault()
$.ajax
url: $(this).getParents('form').first().attr('action')
method: 'PUT'
data:
person:
remove_image: 1 # This will trigger the carrier wave function that remove the uploaded file
.done (data) ->
# You can do plenty if things here, for instance notify the user it's been correctly deleted
Note that this will only work on an edition form, as the url of the AJAX query which has to target the update action is taken from the form. I don't think this is a problem, as on the create form no photos is already uploaded, so there's nothing to delete.
Last thing, you could use the siblings method to find both inputs and the image
I've just started "Build Your Own Ruby on Rails" and I have had to use Google a lot, as the book seems to have a bunch of places where the code just doesn't work. This time, I couldn't find an answer. Okay, so here's the deal. I have a form that looks like this:
new.html.erb:
<%= form_for :story do |f| %>
<p>
name:<br />
<%= f.text_field :name %>
</p>
<p>
link: <br />
<%= f.text_field :link %>
</p>
<p>
<%= submit_tag %>
</p>
<% end %>
It shows up fine when I go to localhost:3000/story/new. The thing is, when I try to type stuff into the form and press "submit," I get this error:
Routing Error
No route matches [POST] "/story/new"
My routes.rb looks like this:
FirstApp::Application.routes.draw do
resources :story
story_controller looks like this:
def new
#story = Story.new(params[:story])
if request.post?
#story.save
end
end
The story_controller stuff for new is straight out of the book. I thought I might have had a solution here, but no dice. Any help would be greatly appreciated.
I'm guessing you meant (note the at sign):
<%= form_for #story do |f| %>
That'll probably take care of your routing issue, but as John mentions, your controller action is a bit off, too. The new action should only load a dummy model and display the new.html.erb page - the saving should take place in a separate action, called create.
Hope this helps!
Edit: Minimal controller code:
class StoriesController < ApplicationController
def new
#Make a dummy story so any default fields are filled correctly...
#story = Story.new
end
def create
#story = Story.new(params[:story])
if(#story.save)
#Saved successfully; go to the index (or wherever)...
redirect_to :action => :index
else
#Validation failed; show the "new" form again...
render :action => :new
end
end
end
First off, Rails is relies on convention over configuration when using singular vs plural names. If you want to follow convention, you have to change the line in your routes.rb to resources :stories, which would generate following routes:
stories GET /stories(.:format) stories#index
POST /stories(.:format) stories#create
new_story GET /stories/new(.:format) stories#new
edit_story GET /stories/:id/edit(.:format) stories#edit
story GET /stories/:id(.:format) stories#show
PUT /stories/:id(.:format) stories#update
DELETE /stories/:id(.:format) stories#destroy
Note, that in this case you would have to rename your controller to StoriesController. However, your routes.rb has resources :story, which generates following routes:
story_index GET /story(.:format) story#index
POST /story(.:format) story#create
new_story GET /story/new(.:format) story#new
edit_story GET /story/:id/edit(.:format) story#edit
story GET /story/:id(.:format) story#show
PUT /story/:id(.:format) story#update
DELETE /story/:id(.:format) story#destroy
As you can see, indeed, there is no route for POST /story/new. I guess, the error that you are getting is triggered by following code in your controller:
if request.post?
#story.save
end
It is quite wrong, because you trying to check for POST request inside the action that is routed to by GET. Just remove this code from your new action and add create action to your StoryController like this:
def create
#story = params[:story]
if #story.save
redirect_to #story, notice: "Story created"
else
render action: "new"
end
end
This should resolve your issue for now. But I strongly recommend using plural stories for your resources, since it will be back to haunt you again.
This is the part that you (and me) have missed from the guide:
There's one problem with this form though. If you inspect the HTML
that is generated, by viewing the source of the page, you will see
that the action attribute for the form is pointing at /articles/new.
This is a problem because this route goes to the very page that you're
on right at the moment, and that route should only be used to display
the form for a new article.
The form needs to use a different URL in order to go somewhere else.
This can be done quite simply with the :url option of form_for.
Typically in Rails, the action that is used for new form submissions
like this is called "create", and so the form should be pointed to
that action.
Edit the form_for line inside app/views/articles/new.html.erb to look like this:
<%= form_for :story, url: stories_path do |f| %>
I have a ASP.Net MVC 2 partial view like the one below,
FORM 1:
<div id="d1">
<% using (Ajax.BeginForm("ManageSources", "Sources",
saveAjaxOptions))
{ %>
... all this form's html markup goes here
<div id="src_Parameters"></div>
<% } %>
</div>
Form 2
<% using (Ajax.BeginForm("FetchParameters", "Sources",
fetchAjaxOptions))
{ %>
hidden fields to send values to the action method go here
.. button to post this form
<% } %>
Now, in the fetchAjaxOptions, i have given the target div to be src_Parameters, which resides inside the form1, when i post the second form, i am being returned a partial view as the only view page, instead of populating the results in the src_Parameters div.
How do i accomplish this. Actually the results of the FetchParameters ajax call should be able to be posted for the ManageSources ajax call.
Where is the problem or will nesting the forms workout since this is using ajax forms.. Kindly suggest me the right procedure to do this task.
You haven't posted your server side code, but I suspect you have forgotten to have set the return type to be a partial view.
public PartialViewResult FetchParameters()
{
//do some stuff
return PartialView(“_ViewName”, viewModel)
}
It could also be that you fotgot to add a reference to the Microsoft Ajax
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
Hey! I'm teaching myself Ruby, and have been stuck on this for a couple days:
I'm currently using MooTools-1.3-compat and Rails 3.
I'd like to replace one button (called "Follow") with another (called "Unfollow") as soon as someone clicks on it. I'm using :remote => true and have a file ending in .js.erb that's being called...I just need help figuring out what goes in this .js file
The "Follow" button is in a div with id="follow_form", but there are many buttons on the page, and they all have an id = "follow_form"...i.e. $("follow_form").set(...) replaces the first element and that's not correct. I need help replacing the button that made the call.
I looked at this tutorial, but the line below doesn't work for me. Could it be because I'm using MooTools instead of Prototype?
$("follow_form").update("<%= escape_javascript(render('users/unfollow')) %>")
ps. This is what I have so far, and this works:
in app/views/shared:
<%= form_for current_user.subscriptions.build(:event => #event), :remote => true do |f| %>
<div><%= f.hidden_field :event %></div>
<div class="actions"><%= f.submit "Follow" %></div>
<% end %>
in app/views/events/create.js.erb
alert("follow!"); //Temporary...this is what I'm trying to replace
*in app/controllers/subscriptions_controller.rb*
def create
#subscription = current_user.subscriptions.build(params[:subscription])
#subscription.save
respond_to do |format|
format.html { redirect_to(..) }
format.js {render :layout}
end
Any help would be greatly, greatly appreciated!
The ID selector should be used if there is only one of those elements on the page, as the Id selector us for unique IDs. A Class selector is what your looking for. Classes are used for multiple elements that have the same styles or same javascript events.
The code to replace Follow with Unfollow would be as follows in Mootools. I am not totally understanding your question, but you will need to assign a ID to the button.
document.addEvent('domready',function(){
$$('follow_form').addEvent('click',function(e){
//Ajax Here
this.set('value','Unfollow');
});
});
Mootools has a different set of functions than Prototype, so most (if not all) code designed for prototype will not work in Mootools. If you want to see the functions in Mootools, I recommend the Docs (its a good read): http://mootools.net/docs/
This code would work as well for you, if you do not/can not add unique IDs to each form element:
$$('input').addEvent('click',function(){
if(this.value == 'Follow') {
//Ajax Here
this.set('value','Unfollow');
}
});