Cant execute coffeescript in modal - javascript

first of all, im still learning Ruby on rails, currently im working on rails 4.2.6.
I have a problem with my code, i have a modal where i want to show the information dynamically with ajax (Calling a method in a controller and showing the information on the modal without closing it) but i have a problem, i cant call any function on the modal.
.col-xs-7
%h5="#{period.name}"
.col-xs-5
%form
.input-group
%input.form-control{type: "text", placeholder: "#{t('reports.periods')}"}/
.input-group-btn
%button.btn.transparent-button.dropdown-toggle{"data-toggle" => |
"dropdown", |
type: "button"} |
= svg_icon('icon-arrow-down')
%ul.dropdown-menu.pull-right
- #batch_id.periods.each do |period|
%li
= link_to period.name, '#', :onclick => "myFunction", id: "#{period.id}_id", value: period.id
.row.actions-container
.col-xs-12
%h4="#{#student_id.name}"
%hr
.row.actions-container
.col-xs-12
%form
= label_tag t('batches.observations')
%br
= text_area_tag 'rejection_comments', #comment.try(:comment) , class: 'form-control', :rows => 10, :cols => 30
- content_for(:page_javascript) do
:coffeescript
myFunction = ->
alert 'hello world'
return
Right now im trying only to call the function 'MyFunction' after i select a period but it throws an error:
myFunction is not defined
But if i do this:
- #batch_id.periods.each do |period|
%li
= link_to period.name, '#', :onclick => "alert('hello')", id: "#{period.id}_id", value: period.id
It works...
Can someone tell me what im doing wrong? I want to do the ajax thing as soon as possible.
Ps: The comment part on the text area is the info i want to get from the controller dynamically.
Thanks!

Related

How to replace inline javascript in rails controller

My existing sessions_controller use inline javascript exit to root_path as follow:
render inline: "<script>window.location.replace('#{url}')</script>"
It worked in Rails 4 but not in Rails 5.
Most document talking about calling javascript in view.
But this is controller.
From what I understand I should replace with
render :js => "myNewJavascriptFunction();"
Which I did tried create myNewJavascriptFunction() in another file eg:
views/sessions/create.js.erb it has error
undefined method `myNewJavascriptFunction' for
Help:
How or Should I put the javascript in views/sessions/create.js.erb
Can we put the javascript in assets to work with controller and how.
Here my existing codes:
In SessionsController
def create
auth = request.env["omniauth.auth"]
user = User.from_omniauth(auth)
session[:user_id] = user.id
if params.permit[:remember_me]
cookies.permanent[:auth_token] = user.auth_token
else
cookies[:auth_token] = user.auth_token
end
# render :js => refresh(root_path) #not work
# redirect_to root_path #not work with JQM
render inline: "<script>window.location.replace('#{url}')</script>" #not work with Rails 5
rescue
render inline: "<script>window.location.replace('#{url}')</script>" #not work with Rails 5
end
views/sessions/create.js.erb
function refresh(url='/') {
window.location.replace(\'#{url}\');
}
menu call
- if login?
%li
%a{"data-panel" => "main", :href => logout_path, "data-ajax"=>"false"} Sign Out
- else
%li
%a{:href=>new_session_path, "data-panel" => "main"} Sign In
%li
%a{:href=>new_identity_path, "data-panel" => "main"} Sign Up
%li
= link_to "Refresh", "#", :onclick=>"window.location.replace('/')"
- if !login?
= link_to image_tag( 'facebook-sign-in-button.png'), '/auth/facebook', rel: "external"
No need to have a views/sessions/create.js.erb
Just replace render inline: "<script>window.location.replace('#{url}')</script>" with render js: "window.location.replace('#{url}')"

Search and display multiple columns when using jquery autocomplete in Rails?

I have successfully integrated Jquery-Autocomplete into my rails app, currently users can search more than 5000+ airports and so far the integration works exactly as desired, however...
Any Airport has multiple columns, currently i am returning the airport name but would like to instead show
**
airport_name - airport_city - airport_iata - airport_icao
**
I have so far used Ryan Bates Railscast to get me started
Episode #102
But amended and tweaked thanks to other resources since his video. Sorry i can't reference them right now but will update my question once i've found links to their instructions.
Either way Autocomplete does work as designed and i have managed to populate a hidden field but i would really like to display more than just the Airport name when searching. I will continue to only save the airport ID.
Any help is appreciated, here is my code.
_form.html.erb
<div class="field">
<%= f.label :departure_airport %><br>
<%= text_field_tag nil, nil, :id => 'claim_departure_airport_name', data: {autocomplete_source: Airport.order(:name).map { |t| { :label => t.name, :value => t.id } } }, class: "form-control" %>
</div>
<%= f.hidden_field :d_airport_id, id: 'd_airport_id' %>
<%= f.hidden_field :a_airport_id, id: 'a_airport_id' %>
claims.coffee
jQuery ->
$('#claim_departure_airport_name').autocomplete
source: $('#claim_departure_airport_name').data('autocomplete-source')
select: (event, ui) ->
# necessary to prevent autocomplete from filling in
# with the value instead of the label
event.preventDefault()
$(this).val ui.item.label
$('#d_airport_id').val ui.item.value
$('#claim_arrival_airport_name').autocomplete
source: $('#claim_arrival_airport_name').data('autocomplete-source')
select: (event, ui) ->
# necessary to prevent autocomplete from filling in
# with the value instead of the label
event.preventDefault()
$(this).val ui.item.label
$('#a_airport_id').val ui.item.value
As you can see i am directly reaching the model data without the need for a dedicated controller although i realise this would be much more intelligent than my current solution as i wish to roll this out in other areas of the platform.
I don't fully understand everything that is happening in the jquery code in my coffee file this was obtained from another source although i forget who to give credit. As far as i know it's taking the ID of the airport and populating the hidden field?
If you can spot how to show other airport database columns to the user that would be great.
Thanks
edit
Also wish to restrict autocomplete from loading the data source into html due to seriously long page load times. A screen shot of what i mean is below.
screenshot of data loading
You can modify the autocomplete source to
<%= text_field_tag nil, nil, id: 'claim_departure_airport_name', data: { autocomplete_source: Airport.select(:id, :name, :city, :iata, :icao).order(:name).map { |t| { label: "#{t.name}-#{t.city}-#{t.iata}-#{t.icao}", value: t.id } } }, class: "form-control" %>
To refactor this a bit, you can move the active record query into a helper
def airport_autocomplete_data
Airport.select(:id, :name, :city, :iata, :icao).order(:name).map { |t| { label: "#{t.name}-#{t.city}-#{t.iata}-#{t.icao}", value: t.id } }
end
and your text field becomes
<%= text_field_tag nil, nil, id: 'claim_departure_airport_name', data: { autocomplete_source: airport_autocomplete_data }, class: "form-control" %>
The main point is here data: {autocomplete_source: Airport.order(:name).map { |t| { :label => t.name, :value => t.id } } }
It builds an array of objects, like [{'label': 'BKK', value: 1}, {'label': 'HAM', value: 2}]
So you either need to add something to the label key, or maybe add a different key and use it later in the select callback.
If you are using rails4-autocomlete Gem. You can easily override from controller.
def autocomplete_profile
term = params[:term]
profiles = Profile.where(
'LOWER(profiles.first_name) LIKE ? OR LOWER(profiles.last_name) LIKE ?',
"%#{term}%", "%#{term}%"
).order(:id).all
render :json => profiles.map { |profile| {:id => profile.id, :label => profile.id, :value => profile.id} }
end

Rails: How to catch ajax success

I googled a lot and was unable to find my mistake. As I just started with JS this might be an easy one. Using: Rails 4
I have a modal with a form that I would like to do stuff after successfully (or not) doing the ajax call. For now just closing the modal.
modal (this works actually works, so I can edit stuff):
.modal.fade{ id: attribute.id, role: 'dialog', tabindex:'-1' }
.modal-dialog{ role: 'document'}
.modal-content
.modal-header
%button{ type: 'button', class: 'close', 'data-dismiss' => "modal" }
%span ×
%h4.modal-title= attribute.name
= form_for attribute, remote: true, html: { class: 'form-inline', id: 'edit_form' } do |f|
.modal-body
.form-group
= f.label :name, 'Name', class: 'form-label', style: 'width: 150px'
= f.text_field :name, class: 'form-control', style: 'width:200px;margin-right: 35px'
.modal-footer
%button{ type: "button", class: "btn btn-default pull-left", 'data-dismiss' => "modal" }
Close
= f.submit 'Create', class: 'btn btn-primary pull-right'
my JS file (dont laugh):
$(document).ready( function($) {
console.log('ready'); # this I *can* see in the console
$('#edit_form').bind("ajax:success", function() {
console.log('great success') # this I *can't* see in the console.
});
});
controller (additional fun fact: The modal is triggered in a view for a different controller, not the one of the modal that I am actually trying to change):
respond_to do |format|
format.js {}
end
So in the end I would like to catch the "error" and "success" callbacks and do sth with it (this I am trying to figure out myself first). What am I doing wrong here?
Thanks a lot for your help - it is really appreciated!
According to the answer of a similar question you might want to try:
$('#edit_form').on("ajax:success", ...
// ^-- instead of .bind
I assume you also have a recent jQuery version, so give this change a shot.

Prompt Message not coming in IE11 form by using simple_form - rails

I am unable to get prompt in IE11 'Please select an item in the list' message when the form is submitted. Though it's not submitting the form, the message is not coming. I am able to get in IE 13, safari, firefox and chrome. It's a specific requirement. Is there anyway to get that done?
Rails version: 4.0.6
simple_form: 3.0.2
= simple_form_for(:report, url: report_create_path, method: :get, html: { class: 'form-horizontal'}) do |f|
= f.simple_fields_for(:q) do |r|
= r.input :search, label: 'Search By', required: true, collection: [['Policy', 'policy'], ['Region / Booth Code', 'code']], input_html: { class: 'search-performance' }
footer
= f.submit 'Generate', class: 'btn btn-primary'
I need to get a popup message like in image, showing the sample of firefox

Autocomplete with typeahead in rails 3

I'm developing autocomplete for a particular form in my rails app; for this purpose I'm using typeahead.js with custom controller method. So far, it works but I need using those values within the form again so that I can press the submit button and the form will be posted and processed by rails normally. How can I do this? Here's the code right now
.page-header
%h1
= #org.name
%small= t('.title')
= form_for #org_admin, |
url: organization_organization_admins_path(#organization) do |f|
.form-group
= f.label t('.user')
= f.hidden_field :user, id: 'user_id'
%input.typeahead{ :type => "text", :autocomplete => "off"}
= f.submit t('.submit'), class: 'btn btn-primary'
= link_to t('.back'), organization_organization_admins_path(#organization)
:javascript
$(document).ready(function() {
$('input.typeahead').typeahead({
name: 'names',
remote: "#{search_organization_organization_admins_path(#organization)}?term=%QUERY",
engine: Hogan,
template: '<p><strong>{{username}}</strong></p>',
limit: 10
}).on('typeahead:selected', function(e, data){
$('#user_id').value = data.id
});
});
So, I would like to populate the :user attribute in the form with the json object returned by the controller
Nevermind, I figured out... the above code is in the right path, except for the call to this line
$('#user_id').value = data.id
Since I'm using jQuery to select the hidden element I had to use the jQuery val function instead
$('#user_id').val(data.id)

Categories