Making a form on collection select - Rails - ruby-on-rails

I am trying to create a form that submits on the collection select option, like when I select a value from the dropdown, it should post, what is posted below is not working,
<%= form_tag edit_zone_management_path, :method => 'get', :id => "bar" do %>
<%= collection_select :dropdown, :id, Server.where(:id => #arr),:id, :server_name, :prompt => true, :selected => #sid %>
<%end%>
Can someone please point out what is missing here?
Addition
There is some coffeescript that is bound to this collection select.
$ ->
$("#dropdown_id").live "change", -> // id of the collection_select
index = this.selectedIndex
uid = window.location.pathname.split("/")
if index == 0
index += 1
response = "{ \"key\": { \"value\" : #{index} } }"
#window.location.replace(uid[0]+ "/" + uid[1] + "/" + uid[2] + "/" + uid[3] + "/" +uid[4])
$.ajax({
type: 'POST',
url: '/configuration/zone_management/updategrid/',
data: response,
contentType: "application/json",
});

It looks like you are missing any handler for your $.ajax call, try adding some:
$.ajax({
type: 'POST'
url: '/configuration/zone_management/updategrid/'
data: response
contentType: "application/json"
success: (response) ->
console.log response
alert "Success fired"
error: (response) ->
console.log response
alert "Error fired"
})
This is just example, so adjust your handlers accordingly!
Good luck!

Related

simple_form select collection populated by AJAX call

In my view I have a simple form with two select lists:
<%= simple_form_for #job, url: jobs_path do |f| %>
<%= f.input_field :types, as: :select, collection: #types, id 'types-select' %>
<%= f.input_field :subtypes, as: :select, collection: #subtypes %>
<% end %>
When a user selects an option from the first list, the second list below should be populated with values from the database based on the above selection.
For this reason, I am making ajax request when a user selects an option from the first list:
$('#types-select').change(function(){
$.ajax({
url: '/subtypes',
dataType: 'json',
type: 'GET',
data: {
type_id: this.value
},
success: function(data) {
console.log(data);
}
});
});
Controller looks like this:
class SubtypesController < ApplicationController
respond_to :json
def index
#subtypes = Type.find(params[:type_id]).subtypes
render json: #subtypes
end
end
At this point how can I fill up the second select with options from #subtypes?
You can populate second dropdown within success callback. Make sure #subtypes is returned in proper json format too.
Controller:
def index
#subtypes = Type.find(params[:type_id]).subtypes
render json: #subtypes.map { |item| { value: item.value } }
end
JS:
$.ajax({
url: '/subtypes',
dataType: 'json',
type: 'GET',
data: {
type_id: this.value
},
success: function(data) {
// Populate second dropdown here
var output = '';
$subtypes.empty().append(function() {
data.forEach(function(item) {
output += "<option>" + item.value + "</option>"
});
return ouput;
});
}
});

AJAX Rendering 400 Error

The goal is to load the comment for each article on my index page using AJAX.
I'm getting a bad request error 400:
ERROR bad URI `/comments/%3C%=%20comment.id%20%%3E?_=1457892605480'.
Index:
#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 %>"}
JS:
#comments.js
var loadComment = function() {
return $('.comment-content').each(function() {
var comment_id = $(this).data('comment-id');
return $.ajax({
url: /comments/+comment_id,
type: 'GET',
dataType: 'script',
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Worked OK!");
}
});
});
};
$(document).ready(loadComment);
$(document).on('page:change', loadComment);
Show:
#comments/show.js.erb
$('#comment-<%= #comment.id %>').append('j render(#comment.content)');
Routes:
resources :articles do
resources :comments do
end
end
When you URLdecode the URL in the error message, you'll get the following:
ERROR bad URI `/comments/<%= comment.id %>?_=1457892605480'.
Seeing that, the error becomes quite clear: the interpolations in your HAML template are wrong. Instead of ERB interpolation style, you need to use the ruby string interpolation style, as described in HAML docs:
%comment-content{ :id => "comment-#{comment.id}", :class => "comment-content", "data-comment-id" => comment.id }
your url needs to be a string:
url: "/comments/" + comment_id

How to send ajax request in rails app without using remote

This is working just fine
<%#= link_to t('.add_html'), 'javascript:void(0);', :class => "line-item", :product => product.id %>
$('document').ready(function(){
$(".line-item").click(function(){
var prod = $(this).attr('product');
$.ajax({
url:'<%#= line_items_url %>',
data: {product_id: prod},
type: 'POST',
dataType: 'script'
});
});
});
But when I use button nothing happens. Please let me know what am I missing here?
<%= button_to t('.add_html'), 'javascript:void(0);', :class => "line-item", :product => product.id %>
:remote => :true just creates an ajax request; you can do your own ajax request no problem:
$("button").on("click", function(){
$.ajax({
url: $(this).attr("href");
success: function(data) { //handle returned data },
error: function(data) { //handle errors }
});
});
I think you are asking a different question (how to get your call working), which I can update the answer to reflect if you wish
You need to prevent default:
$(document).ready(function(){
$("button").click(function(ev){
$.post(this.url); // I'm not sure this is correct
ev.preventDefault();
});
});

How do I turn this link_to_function to link_to in rails 3

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;
});

Why isn't this "ajax:success" event firing?

I have a view with several "Invite" buttons like this:
<div class = "fbinvite_form" id = "<%= friend[:identifier] %>" name = "fb">
<div class = "btn btn-small">
Invite
</div>
</div>
When one of these buttons are clicked an AJAX function is called (invite_friend) :
$('.fbinvite_form').click(function() {
invite_friend();
});
Here's invite_friend (some values are hard-coded as I debug):
function invite_friend() {
$.post('/groups/7/invitations',
{
"recipient_email": "facebook#meetcody.com",
"commit" : "fb",
"fb" : "fb"
},
function(response) {
});
}
Here's the relevant line that is returned from the controller:
render :json => {
:url => signup_with_token_url(#invitation.token),
:id => #invitation.id
},
:status => :created
I can confirm that this json is being rendered correctly. At this point I'm expecting an ajax:success event to fire. I have the following code at the top of my page:
$('.fbinvite_form').bind("ajax:success", function(evt, data, status, xhr) {
...
});
But it's not firing. Any clue what might be going wrong or how to better troubleshoot (I'm a bit of a noob)?
Additional Context
I wanted to add a little bit more as it might help. I had originally built this to work with a form and it worked fine. For some performance reasons I decided to switch to buttons with AJAX. Here's the original form:
<%= form_for([#group, #invitation], :remote => true, :html => { :'data-type' => 'html', :class => 'fbinvite_form', :id => friend[:identifier]}) do |f| %>
<%= f.hidden_field :recipient_email, :value => "facebook#meetcody.com" %>
<div class = "fbinvite btn_list_right" id = "<%= friend[:identifier] %>">
<%= f.submit "Invite", :class => "btn btn-medium btn-primary", :name => "fb" %>
</div>
<% end %>
This has since been replace with all the code you see above the controller snippet.
UPDATE 1
Per Vince's suggestion I have moved the "ajax:success" code into the success function. Here is the original "ajax:success" function:
$('.fbinvite_form').bind("ajax:success", function(evt, data, status, xhr){
var fb_id = $(this).attr('id');
var response = eval("(" + xhr.responseText + ")");
var link_url = response.url;
var id = response.id;
var inv_url = <%= raw('"' + group_url(#group) + '/invitations/"') %> + id;
var picture_url = "https://www.example.com.com/assets/cody_130by130.png";
var desc = <%= raw('"' + first_name(current_user) + " is working with Cody on fitness. Join " + genderizer(current_user, "his") + " group to start tracking your workouts. Cody and the other group members will keep you motivated!" + '"') %>;
send_invite(fb_id, link_url, picture_url, desc, inv_url); return false;
});
And here is what I've done to move the code into the success function. The issue is that I don't seem to have access to "xhr"
$.ajax({
type: "POST",
url: "/groups/7/invitations",
data: {recipient_email: "facebook#meetcody.com", commit : "fb", fb : "fb" },
dataType: "json",
success: function(evt, data, status, xhr) {
var fb_id = $(this).attr('id');
var response = eval("(" + xhr.responseText + ")");
var link_url = response.url;
var id = response.id;
var inv_url = <%= raw('"' + group_url(#group) + '/invitations/"') %> + id;
var picture_url = "https://www.meetcody.com/assets/cody_130by130.png";
var desc = <%= raw('"' + first_name(current_user) + " is working with Cody on fitness. Join " + genderizer(current_user, "his") + " group to start tracking your workouts. Cody and the other group members will keep you motivated!" + '"') %>;
send_invite(fb_id, link_url, picture_url, desc, inv_url); return false;
}
});
Add error handler like this and log the error, this should help diagnose the issue.
error: function(xhr, status, error) {
console.log(error);
}
EDIT
Sorry you need to use .ajax instead of .post.
$.ajax({
type: "POST",
url: "/groups/7/invitations",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
},
error(xhr, status, error) {
console.log(error);
}
});

Resources