Auto close notice: - ruby

In some...controller.rb i have string
redirect_to posts_path, notice: 'Login or register'
In some...views.html.erb
<% if notice.present? %>
<div class="alert alert-info fade in">
×
<strong><%= notice %></strong>
</div>
<% end %>
In application.js i add
$(".alert-info" ).fadeOut(3000);
$(".alert" ).fadeOut(3000);
$(".alert-success" ).fadeOut(3000);
$(".alert-danger" ).fadeOut(3000);
but alert , do not want to close itself
what am I doing wrong ?

I think you are using jquery. You have to call $('.alert').delay(5000).fadeOut(); with in jquery $(document).ready method that ensure script executed after DOM loading.
First be sure that you add your application.js to your layout page.
Add following code
$(document).ready( function() {
$('.alert').delay(5000).fadeOut();
});
demo

Related

making rails submit form_with through AJAX on keypress

I'm trying to build a kind of calculator with rails 5.2.
I need to update results fields while I'm writing my input fields. Everything is working perfect with AJAX if I press enter Key on my keyboard but it doesn't work if I try to automaticly submit the form as soon as a field is modified.
the view input.html.erb
<%= form_with url: achatproprietaire_output_path do |form| %>
<div class="form-group mb-3">
<%= form.label :credits_conso, "Montant des crédits conso", for:"example-helping" %>
<%= form.text_field :credits_conso, id: "example-helping", placeholder: "crédits conso", class: "form-control", id: "crédit_conso" %>
<span class="help-block"><small>en euros par mois</small></span>
</div>
js file calles un application.js
$(document).ready(function(){
$("#crédit_conso").keypress(function(){
//this.form.trigger('submit.rails');
Rails.fire(form, 'submit');
});
});
js.erb file correctly called with enter key
$('#output_col').replaceWith("<%= j render 'output', capacité_emprunt_maximal: #capacité_emprunt_maximal,
montant_mensuel_maximal: #montant_mensuel_maximal,
taux_interet: #taux_interet,
taux_assurance: #taux_assurance %>");
And I have no render or redirect_to in my controller.
I've also tried to put onchange: "Rails.fire(this.form, 'submit')" in the form fields but it submit the form without AJAX.

Else part is not working in Rails ajax form

I have a Rails ajax form to submit.When user will give the correct data it will search the database and do the operation accordingly.If user is giving the Wrong data it should display user to alert message.But it is not happening like that.
I am explaining my codes below.
home.html.erb
<% if current_admin %>
<p class="flash-message"><%=flash[:notice]%></p>
<div class="col-md-6" style="float:none; margin:auto;">
<%= form_for :sdf ,:url => {:action => "scan_report" },remote: true do |f| %>
<% if params[:receipt_no] %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control", :value => params[:receipt_no] %><%= f.submit "Scan Report" %>
</div>
<% else %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control",placeholder:"Receipt No. scan" %><%= f.submit "Scan Report" %>
</div>
<% end %>
<% end %>
<% end %>
controller/homes_contorller.rb
class HomesController < ApplicationController
def home
#sdf=TSdf.new
respond_to do |format|
format.html
format.js
end
end
def scan_report
if #sdf=TSdf.find_by_Receipt_No(params[:sdf][:Receipt_No])
if #sdf && #sdf.HCSY_Status=='YES'
#hcsy=THcsy.find_by_Sdp_Id(#sdf.Sdp_Id)
#hcsy_deatils=THcsyDetails.find_by_HCSY_ID(#hcsy.id)
#woods=THcsyFundTypeMaster.find_by_Fund_Type_Code(1)
#burn=THcsyFundTypeMaster.find_by_Fund_Type_Code(2)
#good=THcsyFundTypeMaster.find_by_Fund_Type_Code(3)
#swd=THcsyFundTypeMaster.find_by_Fund_Type_Code(5)
#photo=THcsyFundTypeMaster.find_by_Fund_Type_Code(6)
end
else
flash[:notice]="Not Found"
end
end
end
In this form its only taking the correct input but if user is trying to give the wrong input the else part is not executing.Please help me to resolve this error and let me to know how can i make this ajax call in below format.
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
Please help me.I am using Rails version 3.2.19.
Here you send AJAX POST request to scan_report, and if it is successful it should render template scan_report.js.erb, and rendered template will appear in json variable in success callback.
But if params are not valid, the same template is rendered, but all instance variables are missing. And probably empty json is returned or an error appears in log.
Anyway, if you'd like to change flash in remote form, you should put custom code in fail callback. Something like
$("#flash").html('<%= j render flash[:notice] %>');

Rails 3 is escaping javascript in an .js.erb file

I have the following in a .js.erb file, being returned after a form being submitted with remote: true.
create.js.erb
$("#flash-notices").html(" <%= escape_javascript(render(partial: "/shared/flash_messages", locals: { form_errors: #artist.errors.full_messages } )) %> ");
$("#flash-notices").fadeIn(300).delay(3000).fadeOut(300);
...
However, what is being returned to the browser is this:
<textarea data-type="text/javascript" response-code="200">
$("#flash-notices").html(" <ul>\n <div class=\"alert alert-success\">\n <li class=\"alert-item\">Artwork saved<\/li>\n <\/div>\n <\/ul>\n ");
$("#flash-notices").fadeIn(300).delay(3000).fadeOut(300);
...
</textarea>
How can I stop the first level of JS escaping which is stopping the jQuery from executing?

Rails form_for in Twitter Bootstrap Modal with AJAX/JSON

I'm having trouble getting a Rails form_for form to work in a Bootstrap modal and update a table with AJAX. I've followed the guide at http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html, to no avail. I've also tried following the advice in the links at the bottom of this question.
On the index view, I have a table of drivers and a button to add a new driver. The button brings up the modal with a form for a new driver. When the form is submitted, I want the modal to close and the new driver to appear in alphabetical order in the drivers table. What's happening now is that the modal comes up and shows the form, but clicking the submit button does nothing. The modal does not close and the new driver is not added to the database.
Here's a summary of app/views/drivers/index.html.erb:
<div>
Add Driver
<%= render 'new_driver' %>
</div>
<div>
<table id="drivers" class="table table-hover">
<thead>
<%= render 'list_header' %>
</thead>
<tbody>
<%= render #drivers.sort_by(&:last_name) %>
</tbody>
</table>
</div>
Here's the modal partial at app/views/drivers/_new_driver.html.erb:
<div id="driverAddModal", class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="driverAddModalLabel">Add Driver</h3>
</div>
<div class="modal-body">
<%= form_for #driver, remote: true do |f| %>
Last Name
<%= f.text_field :last_name %>
<!--more form fields-->
<%= f.submit "Add Driver", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
app/controllers/drivers_controller.rb:
class DriversController < ApplicationController
def new
#driver = Driver.new
end
def create
#driver = Driver.new(params[:driver])
respond_to do |format|
if #driver.save
format.html { redirect_to #driver, notice: 'Driver added.' }
format.js {}
format.json { render json: #driver, status: :created, location: #driver }
else
format.html { render action: "new" }
format.json { render json: #driver.errors, status: :unprocessable_entity }
end
end
end
def index
#driver = Driver.new
#drivers = Driver.all
respond_to do |format|
format.html
end
end
end
app/views/drivers/create.js.erb:
$("<%= escape_javascript(render #driver) %>").appendTo("#drivers");
app/assets/javascript/drivers.js.coffee:
$(document).ready ->
$("#new_driver").on("ajax:success", (e, data, status, xhr) ->
$("#new_driver").append xhr.responseText
).bind "ajax:error", (e, xhr, status, error) ->
$("#new_driver").append "<p>ERROR</p>"
Here are the other links I've checked out:
http://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/
http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
http://mrdanadams.com/2011/partials-ajax-form-submit-rails/#.UVDJuuC8K00
Rails App with Bootstrap Modal View containing form, submit and disappear modal view without reloading page
Displaying errors when a Twitter Bootstrap modal window contains a Rails form helper
"modal form" with bootstrap on rails works partially
Bootstrap modal not dismissing after form submit in Rails
Rails 3.1 and Twitter Bootstrap modal don't play nice?
Unfortunately I just don't know how to apply the advice on those pages to my app. I'm new to Rails and programming in general and this is my first foray into AJAX or JSON.
It seems like you are very new to Rails. In your case, I suggest you go and read the log files when you submit the form. And also log params[:driver] to see if all the fields are there, and watch for validation in your modal. puts driver.errors.inspect after driver.save to see if validation is the cause.
Sum up:
Check log if there is an submit request to your create controller.
output all params to see everything is submitted as expected.
output 'success' in success scope, and output driver.errors.inspect if save fail.
Then you are good to go to see all the bugs.
Oh I suggest you watch RailsCast, they got everything in there.

How can I hide a search button and show a spinner while my AJAX partial loads in rails 3.1?

I have a partial which returns results from the Amazon-ecs API (searches for books). It takes about 2.5 seconds to return values, so I want to add a spinner (and ideally hide the search button) but I've had a tough time getting it to work.
I already have javascript refreshing the partial with the results. I'd just like the button to give me a spinner (and hide the search button) until the partial finishes reloading.
Here is my main view (index.html.erb) which renders a partial of search results, each of which is added temporarily as an object in AmazonItems:
<%= form_tag amazon_items_path, :method => :get, :remote => true do %>
<p>
<%= text_field_tag :query, params[:query] %>
<span id="spinner" style="display:none">
<%= image_tag 'ajax-loader.gif' %>
</span>
<span id="search_button">
<%= submit_tag "Search" %>
</span>
</p>
<% end %>
<h1>Searching Amazon</h1>
<div id="amazon_returned">
<%= render 'amazon_returned' %>
</div>
My only JS code is in the update.js.erb file, which looks like:
$("#amazon_returned").html("<%=j render 'amazon_returned' %>");
I'm sure this is easy, but I can't get it work. Thanks!
EDIT: my partial "_amazon_returned.html.erb" looks like
<table>
<% for amazon_item in #amazon_items %>
<td> amazon_item.title </td>
...ETC...
<% end %>
</table>
You can hook into the before event to do this:
$(function() {
$("form").on("ajax:before", function() {
$("#spinner, #search_button").toggle();
});
});
Then, in your update.js.erb, add this again to toggle them back:
$("#spinner, #search_button").toggle();
Went with Dylan's answer, added the toggle to the update.js.erb and inserted the following into the view:
<script>
$(function() {
$("#search_button").click(function() {
$("#spinner, #search_button").toggle();
});
});
</script>
Very cool! Thanks again for the help.

Resources