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.
Related
I have 2 select tags, the first is Teams and the second is for member ! I want the second select tag to be filled depending on the selection of the Team.
Example :
Team1 has user1 and user2
Team2 has user3 and user4
I want if if I select the team1 the second select tag would have only the values of its members which will be user1 and user2.
PS: I know how to invoke ajax and pass them to controller and deal with params, I just want to know if there is any way I can get the current value in view and pass to the next select tag
You can do by ajax calls and select2 option population, firstly write a change event like(expecting that you already included select2 in js source)
$('#first-select').change(function(event) {
var first_element;
first_element = $(this);
$.ajax({
beforeSend: function() {
$('#second-select').empty();
},
url: 'your ajax url',
type: 'GET',
dataType: 'JSON',
data: {
role_id: first_element.val()
},
success: function(data) {
$('#second-select').select2({
data: data,
placeholder: 'Select User',
allowClear: true
});
}
});
});
create a action to deliver the users list for a given team id in format json.
And it's done.
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 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 have a regular link
<a href="Auth/LogOut" data-role="button">Log Out<a>and I have to specify that it should be navigated to with the POST verb.
How exactly do I do that?
Docs: jQuery Mobile
// using changePage to use POST on submit
$("#LogOut").bind("submit", function() {
if (validateFormData()) {
changePage({
url: "Auth/LogOut",
type: "post",
data: anyDataNeedingPassing
}, false);
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);