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.
Related
I am trying to render a partial from a controller in rails 5 using ajax(on success) but the blank data is passed to ajax after the action renders a partial.
The Same code was working with rails4. I have also updated the responder gem too for rails5.
Controller:
respond_with do |format|
format.html do
if request.xhr?
#images = get_images
session[:prev_images] = submitted_ids
session[:prev_winner] = winner_id
#prev_images = Lentil::Image.find(submitted_ids).sort_by{ |i| i.id }
#prev_winner = session[:prev_winner]
render :partial => "/lentil/thisorthat/battle_form", :locals => { :images => #images, :prev_images => #prev_images, :prev_winner => #prev_winner }, :layout => false, :status => :created
end
end
Ajax:
$(document).on('ajax:success', function (evt, data, status, xhr) {
// Insert new images into hidden div
$('.battle-inner:eq(1)').replaceWith(data);
$('.battle-inner:eq(1)').imagesLoaded()
.done(function () {
// Remove old images
$('.battle-wrapper:eq(0)').remove();
// Div with new images moves up in DOM, display
$('.battle-wrapper:eq(0)').show();
// Hide Spinner
$('#spinner-overlay').hide();
});
_battle_form:
<div class="grid battle-inner">
<%= semantic_form_for :battle, :remote => true, :url => thisorthat_result_path do |form| %>
<% #images.each do |image| %>
<div class="battle-image-wrap grid__cell">
</div>
<% end %>
<% end %>
</div>
Is your request processing as JS?
Try replacing format.html to format.js
It was an issue with jquery-ujs which is no more a dependency for rails>5.1. rails-ujs dependency needs to be used instead.
https://blog.bigbinary.com/2017/06/20/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack.html
//To read data from response
.on('ajax:error', function(event) {
var detail = event.detail;
var data = detail[0], status = detail[1], xhr = detail[2];
// ...
});
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)
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.
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
I have a vote button, which simply displays the amount of votes and by clicking on it, a vote is automatically added. Now I would like to add an Ajax request, so that the page doesn't refresh. Unfortunately I have never used Ajax before and therefor have no idea how to use it with Rails. I tried going through a few tutorials, but nothing seems to help.
view:
<%= link_to vote_path(:the_id => Amplify.all.where(question_id: question.id)[0].id, :the_user_id => #current_user.id), :remote => true do %>
<button class="fn-col-2 fn-col-m-3 amplify">
<%= image_tag "logo-icon-white.png" %>
<p class="count"><%= Amplify.all.where(question_id: question.id)[0].users.count %></p>
</button>
<% end %>
controller:
def vote
#amplify = Amplify.find(params[:the_id])
#current_user = User.find(params[:the_user_id])
if #amplify.users.where(:id => #current_user.id).count != 0
#amplify.users.delete(#amplify.users.where(:id => #current_user.id).first)
else
#amplify.users << #current_user
end
#question = Question.where(id: #amplify.question_id)[0]
#amplify.update(:votes => #amplify.users.count)
#question.update_attributes(:votes => #amplify.votes)
redirect_to root_path
end
routes:
get '/vote' => "amplifies#vote", :as => "vote"
jQuery(document).ready(function($){
$('.amplify').on('click', function(){
var that = $(this);
$.ajax({
url: '/vote',
data: {id: 'your id'},
/**
* Response from your controller
*/
success: function(response) {
that.siblings('.count').first().text(response);
}
});
})
})
I like calling it like waldek does but with coffeescript.
However, in your example, you are using :remote => true which is the unobtrusive way
Basically you are then going into the controller where you will need a format.js
respond_to do |format|
format.html # if you are using html
format.js # this will call the .js.erb file
end
Then create a file vote.js.erb where you can then access your instance variables and write js
console.log('you are here');