Can I provide AJAX with a Rails URL/path?
For example, what I need is url: articles/1/comments/1.
Since I'm experiencing difficulties for some time now making AJAX execute this URL, I wonder if there's a way to use the Rails route I'm familiar with [comment.article, comment].
Note:
I'm loading a DIV using AJAX:
#welcome/index.haml
- #articles.each do |article|
= article.title
- article.comments.each do |comment|
%comment-content{ :id => "comment-#{ comment.id } %>", :class => "comment-content", "data-comment-id" => comment.id }
AJAX:
var loadComment = function() {
return $('.comment-content').each(function() {
var comment_id = $(this).data('comment-id');
return $.ajax({
url: "" ,
type: 'GET',
dataType: 'script',
});
});
};
Rails provide data-remote attribute in form. It works like AJAX and it uses url as you added in form
you can use it like below:
<%= form_for([comment.article, comment], remote: true) do |f| %>
...
<% end %>
you can use like
<%= form_for([comment.article, comment], remote: true) do |f| %>
...
<% end %>
if you are using form_for or if you want to send ajax like:
$.ajax({
})
then you can use
$.ajax({
url : "<%= url_for article_comment_path(article, comment)%>"
})
Related
I'm working on a Rails 6 app, and want to update page view based on a dropdown value selected using XHR. Dropdown must use GET method coz I am calling index action.
I am using form_with which by default uses remote: true.
I am not using local: true.
I tried onchange: "Rails.fire(this.form, 'submit')" - this does send XHR request and receives a response but does not update view.
I tried onchange: "this.form.submit();" - this does a full page reload not utilizing XHR.
Code from app/views/users/index.html.erb
<%= form_with url: station_users_path(station_id: Current.user.home_station), method: :get do |form| %>
<%= form.select :user_status, options_for_select( { "Active users" => "unlocked", "Inactive users" => "locked"}, #user_status ), {}, { :onchange => "Rails.fire(this.form, 'submit')" } %>
<% end %>
Code from app/controllers/users_controller.rb
def index
#user_status = params[:user_status] || "unlocked"
#users = #station.users.send(#user_status) || []
#user_status == "unlocked" ? seperate_managers_from_users : #managers = []
end
In onchange just write one get_station_users() function. Inside that you can use ajax calling.
In forms
<%= form_with url: station_users_path(station_id: Current.user.home_station), id: “form_id”, method: :get do |form| %>
<%= form.select :user_status, options_for_select( { "Active users" => "unlocked", "Inactive users" => "locked"}, #user_status ), {}, { :onchange => "get_station_users()" } %>
<% end %>
Add Script
function get_station_users(){
$.ajax({
type: "GET",
url: "/station_users",
data: { $('#form_id').serialize(), },
dataType: 'script'
});
}
Your response will be as JS. So you can use index.js.erb
I am trying to figure out how to call the update method when the user checks on the check box. I want to update the database by deleting the value for the check box that is stored in the database. Here is my code
<% #items.each do |item|%>
<%if item.email == #user.email%>
<%= form_for #item do |f| %>
<%= f.check_box :to_do, url: update,:value => item.id%>
<%= item.to_do%><br />
<% end %>
<%end%>
<%end%>
you can do something like..
by using checked property..call ajax using jquery
$('input[type=checkbox][id=to_do]').change(function() {
var hall_id = $('#to_do:checked').val();
$.ajax({
url:"/todo",
type:'POST',
//pass any agruments if needed
//data: {"id": pass any data that you need},
beforeSend: function (){
//show the user that something is in progess
$("#to_do").parent().html("Submitting..");
},
success:function(data){
//update user on success/failure
$("#to_do").parent().html("Submitted");
}
});
})
Now,just implement your action on the controller...thats it.
Hope it helps :)
I am trying to pass some parameters from my view via an AJAX call to a custom method fetch_info in my photos controller. My controller does not seem to be receiving the parameters. When I click on an image to initiate the AJAX call, I see the following in my terminal:
Processing by PhotosController#fetch_info as JSON
Parameters: {"id"=>"", "secret"=>""}
Completed 500 Internal Server Error in 267ms
FlickRaw::FailedResponse ('flickr.photos.getInfo' - Photo not found):
app/controllers/photos_controller.rb:38:in `fetch_info'
It looks like the fetch_info method is being called, but the parameters are empty. How should I be passing in my parameters through AJAX?
Here is my view. I also have my javascript in the view for the purpose of just getting this to work.
index.html.erb
<div class="body_container">
<div id="photos_container">
<% #photos_array.each do |p| %>
<%= link_to '#' do %>
<div class='each_photo_container', id='<%="#{p[:id]}"%>' >
<%= image_tag p[:s_url] %>
</div>
<% end %>
<!-- Load Modal onClick -->
<script type="text/javascript">
jQuery(function() {
$('#<%=p[:id]%>').click(function (e) {
//ajax call to fetch photo info
var fetch_id = '<%=p[:id]%>';
var fetch_secret = '<%=p[:secret]%>';
$.ajax({
type: 'GET',
url: '/photos/fetch_info',
dataType: 'json',
data: { 'id' : fetch_id.val(), 'secret' : fetch_secret.val() }
});
return false;
});
});
</script>
<% end %>
<div class="basic_modal">
</div>
</div>
</div>
Here is my photos_controller.rb:
def fetch_info
puts params[:id]
puts params[:secret]
info = flickr.photos.getInfo(:photo_id => params[:id], :secret=> params[:secret])
end
You can use this code:
$('##{p[:id]}').click(function (e) {
//ajax call to fetch photo info
var fetch_id = '#{p[:id]}';
var fetch_secret = '#{p[:secret]}';
$.ajax({
type: 'GET',
url: '/photos/fetch_info',
dataType: 'json',
data: { 'id' : fetch_id, 'secret' : fetch_secret }
});
return false;
})
I'm using rails 3.1 and ruby 1.9.2. Using checkbox_tag I want that when I click on checkbox, a variable (says #post) is set true then it's passed to controller. How can I do this?
Here is an example of jquery and view code of a live edit/save from a view using ajax:
In application.js:
jQuery('#tranx_field').live('change', function() {
var attr_value = $(this).val();
var attr_name = $(this).next("input[id=attr_name]").val();
var tranx_id = $(this).parent().parent().parent().children("input[id=tranx_id]").val();
$.ajax({
url: "/tranxes/" + tranx_id,
dataType: "json",
type: "PUT",
processData: false,
contentType: "application/json",
data: "{\"tranx\":{\"" + attr_name + "\":\"" + attr_value + "\"}}"
});
});
And the view code:
<%= hidden_field_tag 'tranx_id', #tranx.id %>
<div class="row">
<div class="span6 id="left_col">
<b>Salesrep:</b>
<%= text_field_tag 'tranx_field', #tranx.salesrep,:class => "itemfieldsm" %>
<%= hidden_field_tag 'attr_name', "salesrep" %>
<br>
In the view you could add the following
hidden_field_tag 'post', false
check_box_tag 'post', true
in the controller when the form is submitted, you could just assign it:
#post = params[:post]
The hidden value is just to set the default value, which will be overwritten if the checkbox is selected
I have gotten ajax pagination working using mislav-will_paginate with the js found here: https://github.com/mislav/will_paginate/wiki/Ajax-pagination but I have run into a situation that I am not sure how to handle. I have a number of groups (of the same model) and each group has a number of lists that are paginated. I cannot tell which group to load the lists for in the ajax pagination call. This is the code I am using:
function ajaxPagination(){
var container = $(document.body)
if (container) {
container.observe('click', function(e) {
var el = e.element();
if (el.match('.pagination a')) {
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})
}
}
<% #groups.each do |group| %>
<% lists = group.lists.paginate(:page => params[:group_page], :per_page => 5) %>
<% lists.each .... %>
<%= will_paginate lists, :params_name => "group_page" %>
<% end %>
You need to improve your JS to know which 'group' you're clicking.
$("#<%= group %>").html("<%= escape_javascript(render("group")) %>");
See: http://railscasts.com/episodes/174-pagination-with-ajax or read it at: http://asciicasts.com/episodes/174-pagination-with-ajax
$('.group').click(function(){
$.ajax({
type: "GET",
url: "/group",
data: { 'group' : $(this).attr('id') }
success: function(data){
alert( "Success" );
}
});
});