Calling a function in application.js after an AJAX request - ruby-on-rails

Spinning my wheels trying to figure this out. I have a link that when clicked retrieves a form from the server. The form has 3 buttons and 1 text input. I'm trying to get the non-submit buttons to respond to JS which they don't do after the form is returned from the server.
I've create a function in lists.js which the ajax:success is trying to call, but I'm not doing something right. I've tested the function in lists.js and I know it works, I'm just not calling it right.
Here are the relevant files. How do I activate the showPicturePicker function so it can be used after the AJAX response is inserted?
Lists.js
$("#new_list")
.bind "ajax:success", (evt, xhr, settings) ->
$("#list-item").html(xhr)
showPicturePicker
showPicturePicker = () ->
$('#picture').click (e) ->
e.preventDefault()
alert "yeah, you figured it out"
$(document).ready showPicturePicker
_new.html.haml (the form returned from the server)
= form_for [#list, #item], :remote => true, :html => {:class => 'form-inline'} do |f|
.input-append
= f.text_field "name", :class => 'input-large', :placeholder => "Add item to this list"
%button#picture.btn
%span.icon-camera
%button#link.btn{:style => "font-size: 10px;"}
http://
.secondary-fields{:style => "display: none"}
.field.margin
= f.text_field "link", :placeholder => "http://www.link.com", :style => "width: 325px"
.field.margin
= f.file_field "picture"
= f.hidden_field "picture_cache"
.clearfix
= link_to "blah", "#{}", :class => "fuck-me"
= f.submit "Add Item", :class => 'btn', :id => "add-item"
This is a problem i'll need to solve in other places as well and I appreciate the help.

application.js is wrapped with an IIFE (immediately invoked function expression) and variables defined there will not be visible in other files unless you explicitly make them available to the global scope (either by attaching them to window or some other object).
In application.js, try:
#showPicturePicker = ->
...
# or window.showPicturePicker = ->
"Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident."
http://coffeescript.org/#lexical_scope

Related

How to get information from a checkbox back into the DB in Ruby

I'm pretty sure I'm being an idiot here, but I've been out of Ruby long enough that my searching isn't coming up with the right answer.
I have a popup with a checkbox. I want, if the user checks the checkbox, to set a flag in the Users table so that the checkbox doesn't come up again.
I already have the code for if the thing is set, the popup doesn't come up. I'm having trouble getting the checkbox state-change back to the DB...
The checkbox code look like this:
%button.btn.btn-primary.slide_show_next{:type => "button", :data => {:toggle => "modal", :target => "#help_slide_show_2", :dismiss => "modal"}}
Next
.show-slideshow
%label
%input.show-slideshow-checkbox{:type => "checkbox", :checked => "checked"}
Show me this when I view a report.
The relevant coffeeScript is:
$ ->
if typeof(gon) != 'undefined' && gon.show_help_slide_show == true && document.cookie.indexOf("show-slide-show=false") == -1
$("#help_slide_show").modal()
if document.cookie.indexOf("show-slide-show=false") != -1
$(".show-slideshow-checkbox").attr("checked", false)
$(".show-slideshow-checkbox").change( (event) ->
val = $(event.target).prop("checked")
document.cookie = "show-slide-show=#{val}; Path=/;"
$(".show-slideshow-checkbox").attr("checked", val)
)
Look into form_for. That will help you update the model from the view. The code for a haml form_for is below, and the erb equivalent can be found in the form_for documentation. I find that haml documentation isn't as robust as I'd like for certain syntax questions.
= form_for #user, remote: true do |f|
= f.label 'checkbox'
= f.check_box :table_column, autofocus: true
= f.submit

url_for and remote: true

I've got an issue with Rails. I want a select form which render a partial view when clicked. I want the partial views to be effective without refreshing the whole document (Ajax) but it seems that remote: true does not work for me...
What I have currently and refresh the whole document:
= form_tag url_for(action: :index), method: 'get' do
//Storing some informations in html fields for further use
- shops_array = #shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", data: {submit_on_change: true}
What I've tried :
= form_tag url_for(action: :index), remote: true, method: 'get' do
//Storing some informations in html fields for further use
- shops_array = #shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", data: {submit_on_change: true}
How do I apply the remote: true option with url_for? If not possible, I could use some help finding a workaround.
As per the docs you can specify the remote option to the form_tag method, like so:
form_tag(url_for(controller: :charmander, action: :ember), remote: true, method: :get, class: 'pokemon-form') do
# form logic
end
However, this will only trigger the ajax:success event when the whole form is submitted.
From your question it seems to me that you want to re-render some partial when your select value changes. I'm not sure how you use the submit_on_change data attribute, but if I'm correct in assuming that you make it submit the entire form when the select vaule changes then all you need to do is listen for the ajax:success event for the entire form, like so:
$('.pokemon-form').on('ajax:success', function (event, data, status, xhr) {
// Do something with data, which would be the rendered partial returned
// from the server call.
});
Ended up using an onclick and a JavaScript function. Though it may not be the best solution nor the prettier, it works like a charm for me.
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", onclick: 'ajaxSelectedShop('+String(8)+')'

Rails: Setting class and data-tag of an HTML attribute with a single rails method

I'm currently working on a tour interface that guides new users around my site. I have a Tour model that has many TourStops, each of which contains information about a section of the site.
Basically, I'd like to write a function for the Tour model that -- when passed the number of a TourStop -- generates the correct class and data attribute for the HTML element it's attatched to. For example, I'd like
<%= link_to image_tag("new_button.png", tour.stop_data(1), :title => 'Add new asset'), new_asset_path %>
to call a function and return something like
def stop_data(order)
" :class => '#{tour_stops.find_by_order(order).name}',
:data => '{:order => order}'"
end
creating a link_to tag like:
<%= link_to image_tag("new_button.png", :class => 'tour_stop_1',
:data => {:order => 1}, :title => 'Add new asset'), new_asset_path %>
The above code doesn't work. Is something like this even possible? If not, what's a better approach I might take?
The image_tag accepts two parameters. A source, and a options Hash.
What you are trying to do is squeezing your return value from stop_data into this options Hash.
In order to get this to work, you first, need to return a Hash from stop_data, and second, make sure you pass only two arguments to image_tag - the source, and the options.
First:
def stop_data(order)
{
:class => tour_stops.find_by_order(order).name,
:data => { :order => order } # you may need order.to_json
}
end
Second:
link_to image_tag("new_button.png", tour.stop_data(1), :title => "Add new asset"), new_asset_path
This looks like it will work, but it won't, since your'e passing three parameters to image_tag.
When you do the following:
image_tag("new_button.png", :class => "tour_stop_1", :data => { :order => 1 }, :title => "Add new asset")
It looks like you're passing even 4 parameters to image_tag, but in fact they are only two. In Ruby, when the last parameter of a method is a Hash, you don't need to wrap the Hash key/value pairs in curly braces ({}), so the example above is essentially the same as
image_tag("new_button.png", { :class => "tour_stop_1", :data => { :order => 1 }, :title => "Add new asset" })
Now, to get your helper to work with image_tag, you need to merge the options, so they become only one Hash.
link_to image_tag("new_button.png", tour.stop_data(1).merge(:title => "Add new asset")), new_asset_path
Again, we're omitting the curly braces when calling merge, because it's only (and therefore last) parameter is a Hash. The outcome is the same as:
tour.stop_data(1).merge({ :title => "Add new asset" })

Colorbox-rails inline content

After I install colorbox-rails
**followed the directions on this page: http://rubydoc.info/gems/colorbox-rails/0.0.9/file/README.rdoc
**here is what the readme says to use for the link_to
<%= link_to "My superb link", "#", :data => { :colorbox => true } %>
I added this to my link_to
:data => { :colorbox => true }
it works does a popup, but I can't get it to link to the content I want. It will display either the page you are on in the colorbox or an error message "This content failed to load."
I am trying to get a contact form in the colorbox.
I am running Rails 3.2.8
Do
<%= link_to "My superb link",show_contact_path(#contact.id), :data => { :colorbox => true } %>
Edit
You can also do
// Called directly, without assignment to an element:
$(".myElement").colorbox({href:"thankyou.html"});
// Called directly with HTML
$(".myElement").colorbox({html:"<h1>Welcome</h1>"});
http://www.jacklmoore.com/colorbox
Just make sure you create the selector for the element class="myElement"
Also (credit to One Two Three)
If the link is external (ie., going to site other than your own
application's), you'd need to specify the iframe attribute as follows
:colorbox_iframe => true

How to use a specific controller\action on "onchange" for Select_tag in ruby on rails

Im knew on MVC and on Ruby on rail environment
I have this code
<%= select :language, :language_id,
options_for_select([ "Arabic", "English"]),
{:prompt => "#{t('language')}"},
{:onChange => "#{remote_function(:url => {:controller => 'ConfigurationController',:action => "change_language"}
)}"} %>
And I cant make the Select to call this action and make PostBack for the page on on change
after selected index change nothing is happening ?
Since this is a remote function call. can you see in browser's console if there are any errors returned from server.
the syntax of select_tag, you are using looks fine.
Edit:
did u try alerting some thing onchange event? refer this syntax
<%= select_tag "language", options_from_collection_for_select(#collection,'value','name'), html_options = { :onChange=> "alert('');" :style=> "display:block;" } %>
where u can create your collection using,
#collection = ["en","ab"]
#collection = #collection.map { |name, value| OpenStruct.new(:value => name, :name => name) }
What version of Rails are you using? It looks like remote_function was depracated in 3.1 http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/remote_function
Use jQuery to respond to the change event:
jQuery ->
$("#select_id").change ->
$.ajax(
url: "url",
dataType: "json",
data: "data to send")
.done (data) ->
do_something_on_success()
.fail (data) ->
do_something_on_fail()

Resources