Ajax dynamic select dropdown in rails 5 - javascript

Trying to populate US county from database by selected state from same table. Trying to implement in Rails 5 using this approach here is the link
So far I was able to figured out and see call being made and proper data return in browser console, but dropdown never gets updated. I was trying to messing around with different routes but still no luck. Please, any help would be appreciated.
#routes
get 'account/main/_update_weather', :to => 'client/main#_update_weather', :as
=> :client_location_java
get 'account/_location', :to => 'client/main#_location', :as =>
:client_location
#controller ../controllers/client/main_controller.rb
def _location
#weathers = Weather.all
#profile = Profile.new
#county_name = Weather.where("state_code = ?", "AL")
end
def _update_weather
#county_name = Weather.where("state_code = ?", params[:state_code])
respond_to do |format|
format.js
end
end
#Ajax /assets/javascripts/location.js.coffee
$ ->
$(document).on 'change', '#state_select', (evt) ->
$.ajax 'main/_update_weather',
type: 'GET'
dataType: 'html'
data: {
state_code: $("#state_select option:selected").val()
}
success: (data, textStatus, jqXHR) ->
console.log("Dynamic county select OK!")
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
#View for update ../client/main/_update_weather.html.erb
<script>
$("#county_select").empty()
.append("<%=j render(:partial => #county_name) %>")
</script>
<% #county_name.each do |a| %>
<option value="<%= a.id %>"><%= a.county_name %></option>
<% end %>
#view which trying to update ../client/main/_location.html.erb
<% content_for :head do %>
<%= javascript_include_tag 'location', :media => "all", 'data-turbolinks-
track' => true %>
<% end %>
<%= select_tag "state", options_for_select(state_code) {},
{ id: 'state_select' } %>
<%= f.select :weathers_id, options_for_select(#county_name.collect {|a|
[a.county_name, a.id] }, 0), {}, { id: 'county_select' } %>
#Console output
Started GET "/account/main/_update_weather?state_code=CA" for 127.0.0.1 at 2017-07-17 22:49:11 -0700
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 10 ORDER BY `users`.`id` ASC LIMIT 1
Processing by Client::MainController#_update_weather as HTML
Parameters: {"state_code"=>"CA"}
Rendering client/main/_update_weather.html.erb
Weather Load (3.4ms) SELECT `weathers`.* FROM `weathers` WHERE (state_code = 'CA')
Rendered collection of client/weathers/_weather.js.erb [56 times] (0.7ms)
Rendered client/main/_update_weather.html.erb (8.0ms)
Completed 200 OK in 17ms (Views: 12.0ms | ActiveRecord: 3.4ms)

Related

Couldnot access the controller method from javascript in rails

I am having a scenario where Forgot password is displayed in a Modal when click on link from sessions -> new / signin form.
Now I need to add validation for "check if email exists".
For this I added a route, method in users_controller, script in sessions/new as shown below.
With alerts and rails log I came to know that, when I click on button it is not going to users_controller/ checkemail method
and every email is showing as "Email doesnot exists".
Please help me what the mistake I have done?
routes.rb:
devise_for :users, :controllers => {:sessions => 'sessions'}, :path => '', :path_names => { :sign_in => "login", :sign_out => "logout" }
get "/checkemail" => "users#checkemail", as: :checkemail
users_controller.rb:
def checkemail
puts "****************************************"
#checkemail = User.find_by_email(params[:checkemail])
if #checkemail.present?
respond_to do |format|
format.json { render json: "0" }
end
else
respond_to do |format|
format.json { render json: "1" }
end
end
end
app/views/sessions/new.html.erb:
<%= semantic_form_for(resource_name, :url => password_path(resource_name), :remote => true, :format => :json, :html => { :id => 'password_reset' }) do |f| %>
<input type="hidden" id="email_flag" value="0">
<%= f.inputs do %>
<%= f.input :email, :label => 'Your email address', :input_html => { :id => 'user_email_field',:placeholder => "Enter your email..."}%>
<label id="error_explanation1" class="error errorExplanation" style="margin-top:-10px;"></label>
<% end %>
<%= f.buttons do %>
<%= f.commit_button :label => 'Send me that link', :button_html => {:class => 'submit button', :id => 'forgot_password_button', :disable_with => 'Wait...' }%>
<% end %>
<% end %>
<script type="text/javascript">
$( "#forgot_password_button" ).click(function(e) {
var userEmail = $("#user_email_field").val();
var v1 = validateFirstPage();
if(v1){
return true;
}else{
return false;
}
});
$( document ).ready(function() {
$( document ).on( "change", "#user_email_field", function() {
var email = $("#user_email_field").val();
var url = "/checkemail?checkemail="+email;
$.get( url, function( data ) {
$("#email_flag").val($.trim(data));
});
});
});
function validateFirstPage(){
var email_flag = $.trim($("#email_flag").val());
var userEmail = $.trim($("#user_email_field").val());
if(email_flag =="1"){
$("#error_explanation1").html("").fadeOut();
}else{
if(userEmail != "" && email_flag !="1"){
var error_msg = "Email doesnot exists";
$("#error_explanation1").html(error_msg).fadeIn();
} else{
$("#error_explanation1").html("").fadeOut();
}
return false;
}
}
</script>
These are my rails server logs:
Started GET "/login" for 127.0.0.1 at 2016-11-04 11:32:34 +0530
Processing by SessionsController#new as HTML Rendered
sessions/new.html.erb within layouts/home (993.6ms) Rendered
home/_header.html.erb (0.5ms) Rendered home/_footer.html.erb (0.3ms)
Completed 200 OK in 1538ms (Views: 1157.0ms | ActiveRecord: 0.0ms)
Started GET "/assets/application.js" for 127.0.0.1 at 2016-11-04
11:32:36 +0530 RailsDevTweaks: Skipping ActionDispatch::Reloader hooks
for this request.
Started GET "/checkemail?checkemail=user1#gmail.com" for 127.0.0.1 at
2016-11-04 11:32:46 +0530 RailsDevTweaks: Skipping
ActionDispatch::Reloader hooks for this request. Processing by
AccountsController#checkemail as / Parameters:
{"checkemail"=>"user1#gmail.com"} Completed in 1ms
Started GET "/login" for 127.0.0.1 at 2016-11-04 11:32:52 +0530
RailsDevTweaks: Skipping ActionDispatch::Reloader hooks for this
request. Processing by SessionsController#new as / Rendered
sessions/new.html.erb within layouts/home (28.5ms) Rendered
home/_header.html.erb (0.1ms) Rendered home/_footer.html.erb (0.0ms)
Completed 200 OK in 54ms (Views: 48.8ms | ActiveRecord: 0.0ms)
It is not going to controller method.

JQuery File Upload in Rails - Form still sending HTML requests?

I'm trying to do an asynchronous upload using the following form, but micropost#create is responding to an HTML request. Any advice on how to make my upload form send a JS request?
app/views/shared/_micropost_form.html
<%= form_for #micropost, :html => {:multipart => true} do |f| %>
<%= f.file_field :picture, :multiple => true, :name => "file_folder[picture]" %>
<div><%= f.text_area :content, placeholder: "Caption (Optional)", id: "post-micropost-area" %></div>
<div align="center"><%= f.submit "Post", class: "button postbutton" %></div>
<% end %>
<script>
$(document).ready(function() {
var multiple_photos_form = $('#new_file_folder');
multiple_photos_form.fileupload({dataType: 'script'
add: function (e, data) {
types = /(\.|\/)(gif|jpe?g|png|bmp)$/i;
file = data.files[0];
if (types.test(file.type) || types.test(file.name)) {
data.submit();
}
else { alert(file.name + " must be GIF, JPEG, BMP or PNG file"); }
}
});
});
</script>
app/assets/javascripts/microposts.coffee
(Page with form is rendered by static_pages#home - could that be important?)
jQuery ->
$('#micropost_form').fileupload
dataType: "script"
app/controllers/micropost_controller.rb
def create
#micropost = current_user.microposts.new(micropost_params)
#micropost.hashtags = #micropost.content.scan(/#\w+/).flatten.join(", ")
if #micropost.save
flash[:success] = "Post Created!"
respond_to do |format|
format.html {redirect_to root_url }
format.js
end
else
#feed_items = Micropost.all.paginate(page: params[:page]).per_page(10)
respond_to do |format|
format.html { render 'static_pages/home' }
format.js
end
end
end
[EDIT]
app/views/microposts/create.js.erb
<% if #micropost.new_record? %>
alert("Failed to upload <%=j #micropost.errors.full_messages.join(', ').html_safe %>.")
<% else %>
$('#feed').prepend('<%= j render(#micropost) %>')
<% end %>
$('#micropost_form_div').remove();
$('#new-micropost-link').show();
rails server log
Started POST "/microposts" for 130.95.254.26 at 2015-06-09 07:05:02 +0000
Processing by MicropostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"vQQhQEqn3Owt3arYsUTG0u8rrm9AabK7p4xq1N5hCY7SVUU+1oqM82kiEpkys8P+ju4OScp3te15hJOK/yiw5A==", "micropost"=>{"picture"=>[#<ActionDispatch::Http::UploadedFile:0x007f5a808e8fc8 #tempfile=#<Tempfile:/home/ubuntu/workspace/sample_app/RackMultipart20150609-8758-26fuon.png>, #original_filename="bitcomet-logo.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"micropost[picture][]\"; filename=\"bitcomet-logo.png\"\r\nContent-Type: image/png\r\n">], "content"=>""}, "commit"=>"Post"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."name" ASC LIMIT 1 [["id", 1]]
Unpermitted parameter: picture
(0.1ms) begin transaction
(0.1ms) rollback transaction
Gems (among others)
gem 'carrierwave', '0.10.0'
gem 'mini_magick', '3.8.0'
gem 'jquery-rails', '4.0.3'
gem 'jquery-fileupload-rails'
Try this ......
<%= form_for #micropost, :html => {:multipart => true} do |f| %>
<p>
<%= f.file_field :picture, :multiple => true, :name => "micropost[picture]" %>
</p>
<% end %>
<script>
$(document).ready(function() {
var multiple_photos_form = $('#new_file_folder');
multiple_photos_form.fileupload({dataType: 'script'
add: function (e, data) {
types = /(\.|\/)(gif|jpe?g|png|bmp)$/i;
file = data.files[0];
if (types.test(file.type) || types.test(file.name)) {
data.submit();
}
else { alert(file.name + " must be GIF, JPEG, BMP or PNG file"); }
}
});
});
</script>
Hope this will help you.

Cannot upload images with Dropzone.js | Rails 4 and Paperclip

I'm trying to setup Dropzone in my Rails app to upload multiple images. Dropzone seems to appear on the page fine, but when I submit, the correct url is not uploaded to the database. The JSON returns {"message":"success","fileID":"/images/original/missing.png"}. It's using Paperclip's missing image url.
Picture Model
class Picture < ActiveRecord::Base
belongs_to :album
has_attached_file :image,
:path => ":rails_root/public/images/:id/:filename",
:url => "/images/:id/:filename",
:styles => { :small => "160x160>" }
do_not_validate_attachment_file_type :image
end
Pictures Controller
def create
#picture = Picture.create(picture_params)
if #picture.save
# send success header
render json: { message: "success", fileID: #picture.image.url }, :status => 200
else
# you need to send an error header, otherwise Dropzone
# will not interpret the response as an error:
render json: { error: #picture.errors.full_messages.join(',')}, :status => 400
end
end
pictures.js
$(document).ready(function(){
// disable auto discover
Dropzone.autoDiscover = false;
// grap our upload form by its id
$("#new_picture").dropzone({
// restrict image size to a maximum 1MB
maxFilesize: 1,
// changed the passed param to one accepted by
// our rails app
paramName: "picture[image]",
// show remove links on each image upload
addRemoveLinks: true
});
});
pictures/_form
<%= simple_form_for(#picture, :html => {:class => 'dropzone', multipart: true}) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :description %>
<%= f.input :album_id %>
</div>
<%= f.label :pictures, :class => 'control-label' %>
<div class="controls">
<%= f.file_field "images[]"%>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Logs
Started POST "/pictures" for ::1 at 2015-01-03 21:49:10 -0500
Value for params[:picture][:images] was set to nil, because it was one of [], [null] or [null, null, ...]. Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation for more information.
Processing by PicturesController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oM1TCKtz7RGVdJ20qmlYVMXfMuSFylQbRZPkMWlBir8=", "picture"=>{"title"=>"", "description"=>"", "album_id"=>"", "images"=>nil, "image"=>#<ActionDispatch::Http::UploadedFile:0x007ff7d953d7b0 #tempfile=#<Tempfile:/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/RackMultipart20150103-50729-10fo75i>, #original_filename="Space.jpeg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"picture[image]\"; filename=\"Space.jpeg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Picture"}
Unpermitted parameters: images
Command :: file -b --mime '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-eoe314.jpeg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv1.jpeg[0]' 2>/dev/null
Command :: identify -format %m '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv1.jpeg[0]'
Command :: convert '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv1.jpeg[0]' -auto-orient -resize "160x160>" '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv120150103-50729-5ctpcf'
Command :: file -b --mime '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv120150103-50729-5ctpcf'
(0.3ms) BEGIN
Command :: file -b --mime '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-113dzu5.jpeg'
SQL (0.6ms) INSERT INTO "pictures" ("created_at", "description", "image_content_type", "image_file_name", "image_file_size", "image_updated_at", "title", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["created_at", "2015-01-04 02:49:10.698173"], ["description", ""], ["image_content_type", "image/jpeg"], ["image_file_name", "Space.jpeg"], ["image_file_size", 344179], ["image_updated_at", "2015-01-04 02:49:10.397270"], ["title", ""], ["updated_at", "2015-01-04 02:49:10.698173"]]
(16.6ms) COMMIT
(0.3ms) BEGIN
(0.3ms) COMMIT
Completed 200 OK in 359ms (Views: 0.2ms | ActiveRecord: 18.1ms)
I'm also not sure how to fix the error in the second line of the log, which I think might be the problem.
In your create method, replace:
fileID: #picture.image.url
with:
fileID: #picture.id
you will need fileID to be the id of the upload so you can append it in the js to the delete button of each image.
also do you have images: [] in strong params in your controller? because I believe it should just be :image, also if you do that then in your form replace:
<%= f.file_field "images[]"%>
with:
<%= f.file_field :image, multiple: true %>
In Your JavaScript File
$(document).ready(function()
{
Dropzone.autoDiscover = false;
$("#new_upload").dropzone({
// restrict image size to a maximum 1MB
maxFilesize: 10,
// changed the passed param to one accepted by
// our rails app
paramName: "upload[image]",
// show remove links on each image upload
addRemoveLinks: true,
// if the upload was successful
success: function(file, response){
// find the remove button link of the uploaded file and give it an id
// based of the fileID response from the server
$(file.previewTemplate).find('.dz-remove').attr('id', response.fileID);
// add the dz-success class (the green tick sign)
$(file.previewElement).addClass("dz-success");
}
});
});
in your new.html.erb file
<%= f.file_field :image %><br>
<%= f.submit "Upload" %>
in your controller
def create
#upload = Upload.create(upload_params)
if #upload.save
# send success header
render json: { message: "success", fileID: #upload.id }, :status => 200
else
# you need to send an error header, otherwise Dropzone
# will not interpret the response as an error:
render json: { error: #upload.errors.full_messages.join(',')}, :status => 400
end
end

undefined method `category` for nil:NilClass rails 4

In views/offers/index:
<%= f.collection_select :catId_get, Category.order(:name), :id, :name,
{ include_blank: true },
{data:{
dynamic_selectable_url: dynamic_select_offers_path(':catId_get'),
dynamic_selectable_target: '#offer_menu_id'
}} %>
<%= f.collection_select :menuName_get, #offer.Category.try(:menus) || [], :id,:menu_item_name, :include_blank => true %>
In views/dynamic_select/offers/index.json.jbuilder:
json.array!(#menus) do |menu|
json.extract! menu, :menu_item_name, :id
end
In controllers/dynamic_select/offers_controller.rb:
module DynamicSelect
class OffersController < ApplicationController
respond_to :json
def index
#menus=Menu.where(:category_id=>params[:catId_get])
respond_with(#menus)
end
end
end
In javascripts/dynamic_selectable.js.coffee:
$.fn.extend
dynamicSelectable: ->
$(#).each (i, el) ->
new DynamicSelectable($(el))
class DynamicSelectable
constructor: ($select) ->
#init($select)
init: ($select) ->
#urlTemplate = $select.data('dynamicSelectableUrl')
#$targetSelect = $($select.data('dynamicSelectableTarget'))
$select.on 'change', =>
#clearTarget()
url = #constructUrl($select.val())
if url
$.getJSON url, (data) =>
$.each data, (index, el) =>
#$targetSelect.append "<option value='#{el.id}'>#{el.name}</option>"
#reinitializeTarget()
else
#reinitializeTarget()
reinitializeTarget: ->
#$targetSelect.trigger("change")
clearTarget: ->
#$targetSelect.html('<option></option>')
constructUrl: (id) ->
if id && id != ''
#urlTemplate.replace(/:.+_id/, id)
In javascripts/init.js.coffee:
window.initApp = ->
$('select[data-dynamic-selectable-url][data-dynamic-selectable-target]').dynamicSelectable()
document.addEventListener 'page:load', initApp
$ initApp
In db/migrate:
create_table :menus do |t|
t.integer 'hotel_id'
t.string 'menu_item_name'
t.integer 'price'
t.string 'item_type'
end
add_index("menus","hotel_id")#index is used to search
end
create_table :categories do |t|
t.string 'name'
t.integer 'hotel_id'
end
add_index("categories","hotel_id")
end
I am new in rails.I want to populate data on the menu_item dropdown when i select a category from its parent dropdown. Please help me, i have been stucked in this for 2 days.
Started GET "/offers/index" for 127.0.0.1 at 2014-10-29 16:25:57 +0530
Processing by OffersController#index as HTML
←[1m←[35mCategory Load (15.6ms)←[0m SELECT `categories`.*
FROM `categories` ORDER BY `categories`.`name` ASC
Rendered
offers/index.html.erb within layouts/application (15.6ms)
Completed
500 Internal Server Error in 32ms
ActionView::Template::Error
(undefined method `Category' for nil:NilClass):
316:
<div>
317: <%= f.label "Select Menu:" %>
318:
319: <%= f.collection_select
:menuName_get, #offer.Category(:menus) || [], :id,:menu_item_name,
:include_blank => true %>
320:
321:
322:
</div>
app/views/offers/index.html.erb:319:in `block in
_app_views_offers_index_html_erb___717332836_61645344'
app/views/offers/index.html.erb:303:in
`_app_views_offers_index_html_erb___717332836_61645344'
You have not set #offer in your controller, something like:
#offer = Offer.first
Then you can use:
#offer.categories
Not #offer.Category note the down case and plural.

rails 3 dynamic select field with jQuery

using this example on dynamic list https://github.com/sandeepleo11/Dynamic-Select-Menus-in-Rails-3 I managed to get dynamic select in my form where I add a car, so when I select a carname in the next select field I get only car models that belongs to car I selected, Workin fine in this form.
So I decided to get this thing also in my search form, you select a car and based on that you select a car model and get the results. here is the website with search form http://ec2-107-22-183-238.compute-1.amazonaws.com/cars.
the problem here is that when I select a car I get ActionController::RoutingError (No route matches "/dynamic_search/6"): in console, 6 means I picked a car name who's id is 6 and the select field for carmodels displays all models available.
here is some code I have for the search form and dynamic search:
_search.html.erb
<%= form_for #search do |f| %>
<%= f.label :carname_id_equals, "Select Car Make" %>
<%= f.collection_select :carname_id_equals, Carname.order('name ASC').all, :id, :name, :include_blank => 'All' %>
<%= f.label :carmodel_id_equals, "Select Model" %>
<%= f.collection_select :carmodel_id_equals, Carmodel.order('name ASC').all, :id, :name, :include_blank => 'All' %>
<% end %>
dynamic_search.js.erb
$('#search_carmodel_id').empty();
<% for carmodel in #carmodels %>
// alert(<%= carmodel.id %>);
$('#search_carmodel_id').append($("<option></option>").attr("value",<%= carmodel.id %>).text('<%= carmodel.name %>'));
<% end %>
routes.rb
post "dynamic_carmodels/:id" => "cars#dynamic_search"
controller
def dynamic_search
#carmodels = Carmodel.find_all_by_carname_id(params[:id])
respond_to do |format|
format.js
end
end
application.js
jQuery(document).ready(function() {
// jQuery('#search_carmodel_id_equals').html("<option value=''>Select Carmodel</option>");
jQuery('#search_carname_id_equals').change(function() {
var data=$('#search_carname_id_equals').val();
$.ajax({
type: "POST",
url: "http://"+location.host+"/dynamic_search/"+data,
data: data,
beforeSend: function()
{
// alert('hi');
//$('#status').html('<img src="loading.gif">');
},
success: function(response)
{
// alert(response);
// $('#search_carmodel_id_equals').html(html); //dynamic_search.js.erb
// $('#status').html(html);
}
});
});
});
Solved:
routes is the problem:
post "dynamic_carmodels/:id" => "cars#dynamic_search"
should be
post "dynamic_search/:id" => "cars#dynamic_search"
and dynamic_search.js.erb
$('#search_carmodel_id_equals').empty();
<% for carmodel in #carmodels %>
// alert(<%= carmodel.id %>);
$('#search_carmodel_id_equals').append($("<option></option>").attr("value",<%= carmodel.id %>).text('<%= carmodel.name %>'));
<% end %>strong text

Categories

Resources