I want to add an onclick option to link_to method for loading an modal dialog box...i am using rails version 2.3.8 and i searched on google and could not do it. Plz anybody help me?
My link_to method as follows.
<%= link_to 'All countries',{:controller=>'countries', :action=>'new'}, :remote => true %>
If you are using 2.3.8, you don't have :remote => true. You need to use link_to_remote if you are try to do an ajax action.
So it would look something like:
<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}%>
<div id="populate_me"></div>
and your new method would have to handle the ajax request with something like
countries_controller.rb
def new
<do something>
render :update do |page|
page.replace_html 'populate_me', :partial => 'whatever'
end
end
UPDATED
If you want the onclick in addition to the ajax action, you can just pass it into the html options:
<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}, :html => {:onclick => 'alert("some javascript executed before ajax")'} %>
You can add this to the link:
, :class => "pop light", :id => "modal_link"
Then, your JS shows something ilke this:
<script type="text/javascript">
$(document).ready(function() {
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('');
$('a.close').hide();
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
$('body').append('<div id="fade"></div>');
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
return false;
});
$('a.close').live('click', function() {
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
});
return false;
});
$('#modal_link').click();
});
</script>
Related
I'm still relatively new to Rails so please bear with me. How can I refresh the partial and stay at the page instead of rendering only the partial?
In _interaction.html.haml:
%div.vote_up.pull-left
= link_to('', vote_up_deal_path(deal), :method => :post,
:class => 'icon-thumbs-up interaction_button', :id => "vote_up_#{deal.id}")
In 'votes.js':
$.ajax({
type: 'POST',
url: '/deals/' + id + '/vote_up',
success: function() {
//do stuff
}
});
In my deals_controller.rb:
def vote_up
if user_signed_in?
current_user.vote_exclusively_for(#deal = Deal.find(params[:id]))
render :partial => 'deals/partials/interaction', :locals => {:deal => #deal}
end
end
This will redirect me to the page and render the partial instead of refreshing it like an AJAX request should.
Try
= link_to('', vote_up_deal_path(deal), :method => :post, :remote=>true,
:class => 'icon-thumbs-up interaction_button', :id => "vote_up_#{deal.id}")
because :remote says that it is ajax request
I have this link_to_function
= link_to_remote 'Populate Info From ID', :url => {:controller => 'something',
:action => 'populate_from_id'},
:with => "'id=' + $('account_id').value + '&field_prefix=purchaser'",
:update => {:failure => 'account_id_error'}
I have converted many of them in a rails upgrade with , :remote => true, :method => :post
But i dont know how to add the with condition to grab the value out...any ideas
All the AJAX-specific options representing callbacks are gone in Rails 3 link_to helpers. You'll have to write your own javascript to handle more complex remote actions like your example.
Here's a quick rewrite:
# Your template
= link_to 'Populate Info From ID', :url => {:controller => 'something',
:action => 'populate_from_id'}, :id => "#populate_info"
# In javascript, assuming jquery and
# an element #account_id with a data-id attribute
$("#populate_info").on("click", function() {
$.ajax({
method: "POST",
data: { id: $('#account_id').data("id"), field_prefix: "purchaser" }
error: account_id_error
});
return false;
});
Useful blog post: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/
Lots of great documentation here: http://api.jquery.com/jQuery.ajax/
You beat me to it I came up with this
$('.populate_id').click(function(e){
e.preventDefault();
var url = $(this).attr('href');
var failure = $('#' + $(this).attr('failure'));
failure.html('');
var element = $('#' + $(this).attr('element'));
var id = element.val();
var url_extra = 'account_id=' + id + '&field_prefix=purchaser';
$.ajax({
url: url,
data: url_extra,
type: 'post',
error: function (data) {
failure.html(data.responseText);
}
});
return false;
});
I'm using Rails 3.0.9 version, and jquery.
I've been using this gem without a database. It is used only for map display, and display KML file on it. For this I used:
<div id='ajax_map'>
<% #kmlurl="http://mysite/file1.kml" %>
<%= gmaps( :kml => { :data => "[{ url: #{#kmlurl.inspect}}]" } ) %>
</div>
All great shows.
I want to do that after you change the links (# kmlurl), and click on the button, the map updated with this new KML file. I use a separate action js.erb with the following code:
$('#ajax_map').html('<%= #kmlurl="http://mysite/file2.kml" %>'+'<br />'+'<%= gmaps( :kml => { :data => "[{ url: #{#kmlurl.inspect}}]" } ) %>');
But he does not update the DIV. "js.erb" rendered normally, without using the method of gmaps () it normally returns # kmlurl. I tested this same code in the ". Html.erb" in the tags , it loads a new file, but, of course, just when the page loads.
How can I solve this problem?
Solved the problem as follows (in js.erb):
$('#ajax_map').html('<%= escape_javascript( gmaps({:last_map => false}) ) %>');
Gmaps.map = new Gmaps4RailsGoogle();
Gmaps.load_map = function() {
Gmaps.map.map_options.maxZoom = 15;
Gmaps.map.initialize();
Gmaps.map.kml = [{ url: '<%= "#{#kmlurl}" %>'}];
Gmaps.map.create_kml();
Gmaps.map.adjustMapToBounds();
Gmaps.map.callback();
};
Gmaps.loadMaps();
First I would refactor things just a bit.
Say that first bit of code were in your index page. I'd move the setting of #kmlurl into the corresponding controller action:
def index
#kmlurl = "http://mysite/file1.kml"
end
Then (assuming index?) your index view would be simply:
<div id="ajax_map">
<%= gmaps( :kml => { :data => "[{ url: #{#kmlurl}}]" } ) %>
</div>
Then to add a link that will update the map:
<%= link_to 'Other Map', '/othermap', :remote=>true %>
Now you'd create a route in routes.rb:
match '/othermap' => 'foo#othermap'
Then in foo_controller.rb:
def othermap
#kmlurl = "http://mysite/file2.kml"
end
Then create othermap.js.erb:
$('#ajax_map').html(
'<%=
escape_javascript(
gmaps( :kml => { :data => "[{ url: #{#kmlurl}}]" } )
)
%>'
)
That's a quick fix, but what I would REALLY do is strive to make your view code as simple as possible, and do all the real work in the controller. Ideally your view would just be:
<div id="ajax_map">
<%= gmaps( :kml => { :data => #mapdata } ) %>
</div>
set up #mapdata as appropriate in your controller. You've got too much stuff that really belongs in a controller embedded in your view code! Your othermap.js.erb should be equally simplified. i.e.
$('#ajax_map').html('<%= escape_javascript(gmaps( :kml => { :data => #mapdata } ))%>')
I have the below jquery script and I can't pass i value into locales=> :val
$(document).ready(function(){
var i = 1
function more(){
var information= $("<%= escape_javascript(render :partial => 'info', :locals => { :val => i }) %>");
i = i+1;
}
});
Please guide me how to pass javascript variable to rails.
Thanks
If possible values of the variable i are limited, you could generate javascript for every possible value of i. e.g.: (i is in range 1..10)
$(document).ready(function(){
var i = 1
var informationArray = new Array();
<% (1..10).each do |num| %>
informationArray[<%= num %>] = $("<%= escape_javascript(render :partial => 'info', :locals => { :val => num }) %>");
<% end %>
function more(){
var information = informationArray[i];
i = i+1;
}
});
Otherwise, if variable i is not limited in a specific small range, you should use AJAX to send the parameter to the server and retrieve the information for that value.
Can you help me with these codes:
app/views/admin/articles/position.html.haml
- form_tag update_position_admin_articles_path do
.grid_5.alpha{:id => 'article-container'}
%h3 Articles
%ul#articles.connectedSortable
- for article in #articles
= content_tag(:li, article[0], :id => article[1], :class => 'ui-state-default')
.grid_5.omega{:id => 'feature-container'}
%h3 Featured Articles
%ul#features.connectedSortable
- for feature in #features
= content_tag(:li, feature[0], :id => feature[1], :class => 'ui-state-highlight')
%br.clear
= submit_tag "Update Position"
public/application.js
$(function() {
$("#articles, #features").sortable({
connectWith: '.connectedSortable',
update: function(event, ui) {
console.log($(this).sortable("serialize"));
}
})
});
It's two sortable lists and I need to get the serialize parameter of those lists to be passed when I click the submit button but I always get "(an empty string)" on console.log(). I'm using jQuery-ui for this functionality.
Just in case anyone bumped into this same problem.
Solved this problem with this code:
app/views/admin/articles/position.html.haml
- form_tag update_position_admin_articles_path do
.grid_5.alpha{:id => 'article-container'}
%h3 Articles
%ul#articles.connectedSortable
- for article in #articles
= content_tag(:li, article[0], :id => article[1], :class => 'ui-state-default')
.grid_5.omega{:id => 'feature-container'}
%h3 Featured Articles
%ul#features.connectedSortable
- for feature in #features
= content_tag(:li, feature[0], :id => feature[1], :class => 'ui-state-highlight')
= hidden_field_tag 'sort[articles]', ''
= hidden_field_tag 'sort[features]', ''
%br.clear
= submit_tag "Update Position"
public/application.js
$(function() {
$("#articles, #features").sortable({
connectWith: '.connectedSortable',
update: function(element, ui) {
var result = $(this).sortable('toArray');
var data = {};
data[this.id] = result;
document.getElementById('sort_' + this.id).value = result;
}
})
});