I'm experiencing some strange behavior with .bind() and .unbind() in JQuery, even though my situation is seemingly identical to an example given on the JQuery site. In this case, the bind/unbind is applied to a JQuery tab (one of many). When the tab is clicked, it loads a controller action through ajax.
# show.html.erb:
$(document).ready( function(){
var projectNav = function(){
$("#tabs-project .loadingDiv").show();
$.ajax({ url: "<%= url_for(params.except(:action).merge(:action => 'show_project')) %>", dataType: 'script' })
};
$("#projectMenuButton").bind('click', projectNav);
});
# show_project.js.erb
$("#tabs-project .loadingDiv").remove();
$("#tabs-project").append('<%= escape_javascript(render :partial => "profiles/project")%>')
$("#projectMenuButton").unbind('click', projectNav);
The .unbind() part isn't working like that - clicking the menu button again reloads the partial again.
When I change the existing unbind to $("#projectMenuButton").unbind('click');, it unbinds everything including the tab's principal function (to switch the view to the right div).
You have a scope problem... projectNav is only defined within the scope of the $(document).ready, so it is undefined when passed into unbind. A solution:
# show.html.erb:
var projectNav = function(){
$("#tabs-project .loadingDiv").show();
$.ajax({ url: "<%= url_for(params.except(:action).merge(:action => 'show_project')) %>", dataType: 'script' })
};
$(document).ready( function(){
$("#projectMenuButton").bind('click', projectNav);
});
# show_project.js.erb
$("#tabs-project .loadingDiv").remove();
$("#tabs-project").append('<%= escape_javascript(render :partial => "profiles/project")%>')
$("#projectMenuButton").unbind('click', projectNav);
Related
I am trying to build a select menu whose options simply point to URLs:
# Ruby:
form_tag "", :method => 'get' do
select_tag "", options_for_select([["Memberships", memberships_url], ["Transactions", transactions_url]])
end
# jQuery:
$('form').on('change', function() {
$(this).submit();
});
However, this isn't working. What am I missing?
All you are doing is submitting the form which does not process as a redirection you would need an additional hook for the form onsubmit event to process the redirection but based on your concept this seems unnecessary .
How does this work:
$('form select').on('change', function() {
window.location.href = $(this).val();
});
Or all in jQuery I believe you can use
$('form select').on('change', function() {
$(location).attr('href',this.val());
});
Obviously this hook will apply to all form select DOM objects so I would suggest adding an id to the select like so (notice I dropped the form tag as it is not needed for functionality)
select_tag "navigation", options_for_select([["Memberships", memberships_url], ["Transactions", transactions_url]])
$('#navigation').on('change', function() {
window.location.href = $(this).val();
});
You could also simulate a redirect instead of a link click using
window.location.replace($(this).val());
I want to invoke an Ajax call in Rails. I've seen a good way of doing so with the :remote option. I've got this working example:
<%= button_to('Get Transfers', {:action => 'get_transfers', :section_id => params[:section_id]}, :method => :get, :remote => true) %>
However, I don't want the user to invoke the call by pressing a button or clicking a link, but rather invoke it on a Javascript event (hovering over an element).
Is there a way to use :remote => true, but invoke it automatically when hovering over an element? If yes, how?
Option 1
To make the button respond to click and hover over some other div you can try doing the following:
In your view you give the button a unique id and add some class to an element that should be act as a trigger:
<%= button_to('Get Transfers', {action: 'get_transfers', section_id: params[:section_id]}, method: :get, remote: true}, {id: 'remote_hover_button'}) %>
<div class="some_trigger">Hover me!</div>
In your js you want to bind to that trigger element and trigger the click event on the button:
$(document).ready(function(){
$('.some_trigger').hover(function(){
$('#remote_hover_button').trigger('click');
});
});
Option 2
Write the ajax manually by creating a div that you hover and provide it with an url to call:
<div class="some_trigger" data-url="<%= url_for(action: 'get_transfers', section_id: params[:section_id]) %>">Hover me!</div>
Bind to the div and do an ajax call:
$(document).ready(function(){
$('.some_trigger').hover(function(){
$.ajax($(this).data('url'));
});
});
This will actually just trigger the action and not perform anything with the response.
You can bind to the result with something like this:
$(document).ready(function(){
$('.some_trigger').hover(function(){
$.ajax($(this).data('url'))
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
});
});
For more information on ajax function look at the documentation.
I have an error when making a dynamic select. My ajax doesn't work when I change my select.
This is the view code:
<%= select_tag 'cost', options_for_select(Cost.all.map { |c| ["#{c.types}", c.id] }),:id => "cost_select" %>
<script type="text/javascript">
$(document).ready(function(){
$("#cost_select").live('change',function(){
$.ajax({
url: "finances/cost_type",
type: "GET",
data: {'cost=' + $('#cost_select option:selected').value() },
})
});
});
</script>
Im my finances controller, I have this:
def cost_type
#places = Place.find_by_cost_id(params[:cost])
respond_with #places
end
I make the cost_type.js.erb file, and my response is in js.
My problem is when i change the select tag dont active no one action, how is the problem whit the code in my searchs i find this code working but what is the problem?
UPDATE:
my routes.rb contains:
get "finances/cost_type" => "finances#cost_type"
I solved my original question with the following:
$(document).ready(function(){
$("#cost_select").change(function(){
$.ajax({
url: "finances/cost_type",
type: "GET",
data: {cost: $("#cost_select option:selected").val() },
})
});
});
With this, I received a valid response (which I verified via firebug):
$("#cost_select").after("<select id="from_money" name="from_money"><option value="2">Luz</option></select>
");
However, the data isn't appearing in my view. I tried putting it in a different <div> but the <select> won't appear.
I don't know what is wrong, please provide me with any possible suggestions.
change your javascript to
$(document).ready(function(){
$("#cost_select").live('change',function(){
$.ajax({
url: "/finances/cost_type",
type: "GET",
data: { cost: $('#cost_select').val() }
})
});
});
the extra / before finances makes sure that you're using absolute paths. the data part is also wrong as pointed out in one of the comments but this is a cleaner version.
I am trying to delete an instance of my Rails model with Ajax.
It happens on the click of a button and my code is as shown below:
$("#button").click(function(){
$.ajax({
type: "POST",
url: "/slot_allocations/" + slotallocation_id,
dataType: "json",
data: {"_method":"delete"},
complete: function(){
$( "#SlotAllocationForm" ).dialog( "close" );
alert("Deleted successfully");
}
});
});
I am able to delete it successfully, however the delete method is always followed up by a post request to the server to create a new model with the existing data. These are the requests to the server.
1. POST http://localhost:3000/slot_allocations/1009 [HTTP/1.1 204 No Content 57ms]
2. POST http://localhost:3000/slot_allocations [HTTP/1.1 302 Found 111ms]
3. GET http://localhost:3000/slot_allocations/1010 [HTTP/1.1 200 OK 185ms]
#1 happens on the click of my button. However, I am not too sure why #2 and #3 occur.
There are two buttons in the view:
<button id="button">Delete</button>
<div class="actions"><%= f.submit %></div>
Assuming your button is inside of a form, clicking it is probably submitting that form in addition to firing the ajax request.
What you want to do is prevent the default action of clicking the button, which is submitting the form.
Change the function() parameter to function(event), then add an event.preventDefault() call:
$("#button").click(function(event){
$.ajax({
type: "POST",
url: "/slot_allocations/" + slotallocation_id,
dataType: "json",
data: {"_method":"delete"},
complete: function(){
$( "#SlotAllocationForm" ).dialog( "close" );
alert("Deleted successfully");
}
});
event.preventDefault();
});
You can use:
type: "DELETE"
instead of:
type: "POST"
and remove
data: {"_method":"delete"}
I want to show modal window on click of link but also want to do ajax request to get the object which needs to be shown on modal window.
I am getting response with the content which needs to be shown on modal window but it is not popping up as modal window probably the script is not getting executed.
Code
Main Page
<%= link_to "New Topic", "#", :class => 'btn primary float-right bootstrap-popover' %>
<div id="modal_form_container"></div>
Javascript Code
$('a.bootstrap-popover').live('click', function(){
$(this).unbind('click');
$.ajax({
url: "/topics/new",
type: "GET",
dataType: "html",
complete: function() {
$('loading').hide();
},
success: function(data) {
},
error:function() {
}
}); // End of Ajax
new.js.erb
$('#modal_form_container').html("<%= escape_javascript( render :partial => 'new_form')%>");
$('#modal_form').modal('show');
This new_form page contains content to be shown on modal window
Can anybody help?
Is it because the loading element is not being hidden?
$('loading').hide();
Should this not be something like:
$('#loading').hide();
I think you have to write something like following code after your ajax request gets success.
$('#PopupBoxId').modal('show'); // Show the pop-up (modal)
$('#disable_layer').modal('show'); // Show the black overlay
We have to manually show the pop-up after the ajax request handling.. As per my small experience in bootstrap.
:)
Hope it works for you.
Have you looked into the Bootstrap Modal Manager? You can use it like so:
$("a.open-with-ajax-loader").live('click', function(e){
e.preventDefault();
$('body').modalmanager('loading');
$('#id-of-modal-div').modal({
remote: '/url/to/load'
});
});
You can see this in action on the live demo page for the Bootstrap Modal Manager ( scroll down a bit, look for the AJAX demo ).