Rails AJAX loads entire page into 'update' div - ruby-on-rails

I wanted some code that would automatically reload the posts and insert them into the div post_container:
<%= link_to_remote "Update", {:action => 'ajax_update', :id => #posts, :update => 'post_container'}, :confirm => "Are you sure?" %>
This rails snippet in my home.html.erb actually takes the entire page (title, head, body tags) and places it inside of the div post_container. Why? Also, as far as I can tell, the ajax_update function doesn't even get called.
How would I do what I am trying to do? And why is this entire page loading happening? I'm using Rails 2.3.11
(edit: also, there is no confirm dialog when you click the link.)
EDIT 2:
the html output of the code snippet:
<a confirm="Are you sure?" href="#" onclick="new Ajax.Updater('post_container', '/home', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('uaqM0Ie8to5pprvE6WcF416DN0vNeyO7Xa+JM6VZFY4=')}); return false;">Update</a>

In your controller action, use :layout => false
def ajax_update
#posts = Post.find(#posts)
render :layout => false
end

Found the correct way to do it:
<%= link_to_remote "Update",:update => 'post_container', :url => {:action => 'ajax_update', :id => #posts, }, :confirm => "Are you sure?" %>
Based on information from the Rails 2.3.11 API documentation:
http://api.rubyonrails.org/v2.3.11/classes/ActionView/Helpers/PrototypeHelper.html#M002185
Also, the periodically_call_remote method found on that page is also useful for automatic calls that don't require clicking.

Related

Rails: How to change this link into a button?

Right now I can call a method using ajax (:remote=> 'true') at awisprotect_path by simply clicking on the "x" in this link
<%= link_to "x",
awisprotect_path,
:remote => true,
:method => :post,
%>
The controller action renders jquery so the response is included into the html in the view
<div class="awishanswer">
</div>
That's all working fine. However, instead of having an "x" to click, I wanted the user to click a button and get the same result. So I essentially just wanted to put the link info
<%= link_to "x",
awisprotect_path,
:remote => true,
:method => :post,
%>
into this button
<button class="btn small primary" >
check
</button>
So I created this form and put it in a partial
<%= form_tag(:controller => "sessions", :action => "awisprotect", :remote => true, :method => "post") do %>
<button type="submit" class="btn small secondary">check awis</button>
<% end %>
but the problem is that the controller action that renders js is not putting the result of the action into the html div. Instead, it's redirecting to a blank page and then printing the jquery method with the result that I was checking for with the controller action. the blank page just shows this...
$('div.awishanswer').html(' html to be inserted in div');
Can anyone explain?
In the url it says
http://localhost:3000/awisprotect?method=post&remote=true
in the view file
<div class="awishanswer" id="awishanswer">
<% form_remote_tag :url => {:controller => "sessions", :action => "awisprotect"},
:html => {:method => "post"}, :update => "awishanswer" do %>
<input type="submit" class="btn small primary" value="check" />
<% end %>
</div>
in the action
def awisprotect
#flag = params[:flag] // suppose sending parameter flag from form
// do something
render :partial => 'partial file containing html to send to view'
end
The form will be submitted when the submit button is clicked.
the action will send the html contained in partial file.
the form will update the div with id provided in form with the html code send back from action.
EDIT:partial file
<%if #flag%>
// include some html
<%else%>
// include some other html
<%end%>
The reason your getting a problem is probably because of your usage of the form_tag helper uses the :remote and :method values inside the url generation instead of being handled be the form. The correct usage would probably be like this:
<%= form_tag({:controller => "sessions", :action => "awisprotect"},
:remote => true,
:method => "post")
However, Rails already has a helper method to create a button to submit data called button_to. It basically takes the exact same arguments as the link_to helper so I would probably use it like this in your case:
<%= button_to "x", awisprotect_path, :remote => true, :method => :post %>
The :method argument could possibly even be left out because I think the button_to helper defaults to the POST protocol.
You can disguise a link as a button, using some CSS. Here's a nice article.
This might be better than all these experiments with partials and forms. :-)
I'm thinking you didn't wrap the options for form_tag properly. Try something like this:
form_tag( { :controller => :sessions, :action => :awisprotect, :method => post }, { :remote => true } ) do ....
It may or may not also help to use button_tag.

Disable link_to tag in Rails3+

I used the following code:
<%= link_to image_tag("edit.png", :alt => "Edit"), edit_user_path(user) %>
I want to disable this link and image, so I added :disabled=>true to the code, but it's not disabling. Why not, and how do I disable them?
I'm not sure what #lamrin wanted with this question, but I suppose that it is something like this:
<%= link_to_if condition?, image_tag("edit.png", :alt => "Edit"), edit_user_path(user) %>
With this code above, the image would have a link if the condition? is true
In my case this code below worked (a more complicated example):
link_to_unless disabled, (content_tag :div, "", :class => "vote " + vote_class, :title => title), resource_user_path({ :id => resuser.id, :resource_user => {:id => resuser.id, :resource_id => resource_id, :user_id => current_user_id, :vote => vote_value}}), :remote => true, :method => http_method
This link may also help with this approach:
http://railskey.wordpress.com/2012/07/19/rails-link_to-link_to_if-and-link_to_unless/
Unlike buttons, hyperlinks cannot be "disabled". You can do the following though, assuming you have jQuery included on your pages:
<%=link_to image_tag("edit.png", :alt=>"Edit"), edit_user_path(user), :id => "mylink" %>
Add the following Javascript to your page:
$('#mylink').click(function(e){
e.preventDefault();
});
In answer to your question, there is no :disabled option for the link_to helper in Rails, and it is not a valid attribute for a elements either. I believe the reason people tend to get confused with this in Rails is that ":disabled => true" does work IF you are using Bootstrap. So to fix this issue you can either follow Gupta's approach, or just add Bootstrap (which will give you some default CSS as well, so people don't get frustrated trying to click the link)!
Re: link_to method in rails: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to)
Re: the "disabled" attribute on a elements: Is 'disabled' a valid attribute for an anchor tag
Re: Bootstrap "disabled" class or attribute with bootstrap: http://getbootstrap.com/css/#anchor-element-1
1)One solution is to render just image_tag when you do not want link and use link_to when u want link to be click enabled. you can use instance variables to control what to render.
2) or use Javascript as suggested.
Use 2 if you want to dynamically do it.
You may use conditional link_to:
<%=
link_to_if(#current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
link_to(#current_user.login, { :controller => "accounts", :action => "show", :id => #current_user })
end
%>

Issue with using link_to :remote - Rails 3

I am using link_to :remote to update one of the div elements on the HTML. This is just a beginner's code. However, the update does not occur on clicking the link. Here is the code:
class SampleController < ApplicationController
def updater
render :text => Time.now
end
end
this is the list.html.erb:
<script type = "text/javascript" src = "/javascripts/prototype.js">
<%= link_to "Hello Testing",
:update => "test_id",
:url => {:action => 'updater'},
:remote => true
%>
<div id="test_id"></div>
So on click the link "Hello Testing", the URL in the browser changes to:
http://localhost:3000/samples?remote=true&update=response_id&url[action]=updater
However, the div element that I am trying to set to the current time does not occur on the UI. What can be the issue here?
Updated the post with:
routes.rb: http://pastebin.com/wmKsa1DD
Generated HTML Code : http://pastebin.com/stU3FpL8
HTML Response in Firebug: http://pastebin.com/WjsB7zAh
Using url_for does not change the behaviour.
please use url_for:
<%= link_to "Hello Testing", url_for(:action => :updater),
:update => "test_id", :remote => true %>
I'm not 100% sure, but I don't think that :update is going to work, since Rails3 now mainly relies on ujs.
The "rails way" to update your div would look like (jquery) :
$('div#test_id').bind('ajax:complete', function(event, xhr) {
$(this).html($.parseJSON(xhr.responseText));
})
1: You should include also rails.js file. Ordinary in Rails it makes like this:
<%= javascript_include_tag :defaults %>
2: I prefer to use this naming for urls: updater_samples_path or [:updater, :samples]
3: You should show your routes. If updater method using not GET method, then you should define it:
<%= link_to "Hello Testing", :update => "test_id", updater_samples_path, :method => :put, :remote => true %>
4: Use FIREBUG to se your AJAX responses. So you can easily debug your app. Also you can show us its response, so we will better understend situation

Convert snippet to Rails 3

I found a wonderful article
But it uses rails version previous to rails 3.
In particular, this snippet:
<%= link_to_remote( "click here",
:update => "time_div",
:url => { :action => :say_when },
:position => "after" ) %>
I converted it to this:
<%=button_to 'Click',:remote=>true,:update=>"time_div",:position=>"after",:action=>"say_when"%>
But, there's something wrong.The entire page is being rendered afresh.
What should be done to make it work as described on that site?
it is not button_to, it is link_to 'Click', :remote => true. Also you have to add csrf_meta_tag in the head tag in the layout for Rails 3. See link
In your layout <%= csrf_meta_tag %> And
link_to "some action", my_action_path(#post), :remote => true
For details Try this link
http://www.themodestrubyist.com/2010/02/24/rails-3-ujs-and-csrf-meta-tags/

Multiple submit buttons with ajax

First of all, I'm new at Ruby on Rails, so if there's a better practice than what I'm doing, please let me know.
What I'd like to do is to have multiple ajax submit buttons to perform different actions for a list of items with check boxes. So, when I select as many check boxes as I want, then I can choose what to do with them.
I could partially solve this using ajax as follows:
remote_form_for :profile, :url => {:controller => 'announcements', :action => 'deactivate'}, :html => { :method => :put} do |f|
f.submit 'Publish', :confirm => 'Are you sure?'
#Then the list
This works great. What I'd like to do now is to add another "submit" or button, so I can perform several actions, so I guess the :url statement at the remote_form_for will be replaced for something like that per each button. For example:
Publish button: perform some action in some controller.
Deactivate button: perform another action.
Mark as Read: perform another action.
Is it clear?
add as many "submits" as you like. All submits have the 'name' in the input tag set to 'commit' and the value set to the label. So you can check by looking in the params submitted:
remote_form_for :profile, :url => {:controller => 'announcements', :action => 'deactivate'}, :html => { :method => :put} do |f|
f.submit 'Publish', :confirm => 'Are you sure?'
f.submit 'Something Else"
# Then the list
in the controller
def deactivate
case params[:commit]
when 'Publish' then do something
when 'Something Else' then do something else
end
end
Finally, I could solve it by myself.
It's well known there's a bug for multiple submit buttons on ajax forms. I used the hidden workaround as explained here.
Thanks,
Brian

Resources