How to show loading spinner in on ajax request? [duplicate] - javascript

This question already has answers here:
How to show loading spinner in jQuery?
(25 answers)
Closed 6 years ago.
Hello I have included given html code
#expressShippingCalculation
%li.list-group-item
%label
%input#shipping_method3{:name => "shipping_method", :type => "radio", :value => "1"}
Shipping
%small (Delivery within 4-5 days)
%li.list-group-item#method4
%label
= form_for #order, :url => update_express_shipping_path,:method => 'patch', :html => { :id => "shippingDetails" }, :remote => true do |form|
= form.radio_button :express_shipping, true, :value => true, :id => 'shipping_method4', :name => 'shipping_method'
Express Shipping
%small.maroonColorText (Additional Charge of USD 10 applicable.)
#spinner.spinner{:style => "display:none;"}
%img#img-spinner{:alt => "Loading", :src => "spinner.gif"}/
and js code is
$('#expressShippingCalculation input').change ->
if $('#shipping_method4').is(':checked')
additionalAmountExpress()
data = $('#shippingDetails').serialize()
expressValue = true
else
$('#additional-charge').hide()
expressValue = false
$.ajax
url: '/update_express_shipping?expressShipping=' +expressValue
type: 'PATCH'
return
Now I need to show loading spinner on my ajax request. lease guide me how I will include given code in my ajax request
$('#spinner').bind('ajaxSend', ->
$(this).show()
return
).bind('ajaxStop', ->
$(this).hide()
return
).bind 'ajaxError', ->
$(this).hide()
return
Please guide me how to include this code.

$(document).ajaxStart(function(){
$('#spinner').show();
});
$(document).ajaxComplete(function(){
$('#spinner').hide();
});
$(document).ajaxError(function(){
$('#spinner').hide();
});
► ajaxStart
► ajaxError
► ajaxComplete

Related

Rails/Javascript: Data attribute not returned through partial, but present in DOM

I am trying to display the value of a select field for shipping costs beneath the field. Thanks to #Vasfed I am tying to use data attributes and javascript. But while the data attribute is rendered in the DOM while loading th page it is not returned in the data returned for the AJAX call when inspecting console or resources.
In DOM:
<select id="shippingservices_select" name="cart[shippingservice_id]"><option value="">select a carrier</option>
<option value="7" data-price="3.9">UPS</option>
<option value="19" data-price="10.0">DHL</option>
</select>
The fetched partial:
$("#shippingservices_select").empty()
.append("<option value=\"7\">UPS<\/option><option value=\"19\">DHL<\/option>");
I am using the following ajax call:
$(document).on("change", "#lands_select", function(event){
jQuery.ajax({
url: "/carts/update_shipping/" + event.target.value,
type: "GET",
error: function (xhr, status, error) {
console.error('AJAX Error: ' + status + error);
},
success: function (response) {
console.log(response);
}
});
});
Which should return both value and data attribute, for the form:
<%= form_for :cart, :url => {:action => "show_shipping"}, :html => { :method => "get", :remote => true } do |f| %>
<%= f.collection_select(:land_id, Land.all, :id, :name, {:prompt => "select a country"}, {:id => 'lands_select'}) %><br>
<%= f.select(:shippingservice_id, options_for_select(#shippingservices.collect { |s| [s.name.titleize, s.id, {'data-price' => s.price}] }), {:prompt => "select a carrier"}, {:id => 'shippingservices_select'}) %><br>
<% end %>
Shipping: €<div id="shipping_cost"></div><br>
with the update_shipping.js.erb view:
$("#shippingservices_select").empty()
.append("<%= escape_javascript(render(:partial => #shippingservices)) %>");
and the rendered partial _shippingservice.html.erb of:
<option value="<%= shippingservice.id %>" data-price="<%= shippingservice.price %>"><%= shippingservice.name.titleize %></option>
In the controller I have:
def update_shipping
...
respond_to do |format|
format.js
end
end
Following my partial _shippingservice.html.erb I should get both value and data attribute, but I do not. I think this is the reason why:
$(document).on("change", "#shippingservices_select", function(event){
var price = $(event.target).data('price');
$("#shipping_cost").html(price);
});
Does not return the value of data-price.
How can I get this to work? Thank you in advance.
UPDATE
I was trying to troubleshoot it and things appear to be quite strange.
Both selectors display data in the DOM. The shipping service select field which get’s loaded on page load shows everything. On changing the land selector, the partial which gets loaded and which I can inspect in console does only display option value + name, but when changing the _shippingservice partial I found out that the code which gets loaded through AJAX appears not to be generated by the partial referenced in the JS Ajax call, since I can change the code inside without producing any effect on the delivered payload.
But when substituting
<%= escape_javascript(render(:partial => #shippingservices))%>
By
<%= escape_javascript(render ‘carts/shippingservice’)%>
Nothing is displayed and loaded.
You can check what partials are getting rendered on the terminal where you are running rails. Looks like you have more than 1 possible partial for shipping services.
You can also specify which partial to use instead of letting rails guess:
render partial: 'carts/shippingservice', collection: #shippingservices, as: :shippingservice

Run controller action with confirm form in RoR with haml

Is there any possible way to run controller action with confirm form before it?
I'd like to ask user is he/she really sure to do following action. And after confirmation run this action. In other case just do nothing.
I already tried this code:
= form_tag( '#', onclick: "confirm('#{text}')", :controller => :payments, :action => :pay, :subscription_id => subscription_plan) do
= hidden_field_tag 'current_subscription', subscription_plan.id
.payment_button= image_submit_tag "/images/popup/payment/#{label_img}", :value => label.to_s, data: { disable_with: "Please wait..." }
And I'm interesting in is there any way to do it without JavaScript?
Yes there is way
.payment_button= image_submit_tag "/images/popup/payment/#{label_img}", :value => label.to_s, data: { confirm: 'Your confirm message', disable_with: "Please wait..." }
OR another way is
= form_tag( '#', onsubmit => "return confirm('Are you sure?');", :controller => :payments, :action => :pay, :subscription_id => subscription_plan) do

Rails Ajax Refresh Partial while persisting params

I have a Rails app with a controller/view called "calls". Here is the basic controller action for index:
calls_controller.rb
def index
if params[:region].present?
#assigned = Call.where(region_id: params[:region][:area]).assigned_calls.until_end_of_day
#unassigned = Call.where(region_id: params[:region][:area]).unassigned_calls.until_end_of_day
else
#assigned = Call.assigned_calls.until_end_of_day
#unassigned = Call.unassigned_calls.until_end_of_day
end
end
Here are my views:
index.js.erb
$('#active').html("<%= escape_javascript render :partial => 'calls/assigned_calls', :locals => {:assigned_calls => #assigned} %>");
$('#inactive').html("<%= escape_javascript render :partial => 'calls/unassigned_calls', :locals => {:unassigned_calls => #unassigned} %>");
$(".select").select2({
placeholder: "Select One",
allowClear: true
});
index.html.erb
<div id="active">
<%= render "assigned_calls" %>
</div>
<div id="inactive">
<%= render "unassigned_calls" %>
</div>
<script>
$(document).ready(function() {
setInterval(function () {
$.ajax('calls/<%= params[:region][:area] %>');
} , 5000);
});
</script>
_assigned_calls.html.erb (view code omitted)
<%= form_tag calls_path, :method => 'get' do %>
<p>
<%= select_tag "region[area]", options_from_collection_for_select(Region.order(:area), :id, :area, selected: params[:region].try(:[], :area)), prompt: "Choose Region" %>
<%= submit_tag "Select", :name => nil, :class => 'btn' %>
So what's happening is on page load if I do not have the params of :region passed it sets the calls without being scoped by region. If region_id is present then it scopes calls where region_id is "1" or whatever the Region ID is that is passed from the submit_tag.
This works fine in the controller and view, however here's my problem. My index.html.erb I need to refresh the partials WITHOUT disturbing the params passed. So on setInterval I need to figure out how to reload the partials while persisting the params passed in the URL.
I tried to figure this out using a setInterval method but I'm not sure what I'm doing here 100%.
Can someone give me some advice on how to refresh the partials every 5 seconds while persisting the params so my instance variables persist through refresh?
If you need more context and/or code please let me know.
Update
Trying to rework the javascript based off an answer from a user and here's what I have.
<script>
$(document).ready(function() {
setInterval(function () {
$.ajax({
url: 'calls_path',
type: "GET",
data: { "region": '<%= #region.html_safe %>' }
}), 5000);
});
});
</script>
The page will load but when it tried to trigger in the chrome inspector I get:
calls?utf8=✓&region[area]=3:2901 Uncaught SyntaxError: Unexpected token )
Maybe this is a JS syntax error or I'm not closing the function properly.
If I understood properly, you want to have your parameters somehow pipelined through AJAX call to your controller, back to your js.erb file where it refreshes the partials?
My advice is to set passed parameters as instance variables in your controller like this:
calls_controller.rb
def index
if params[:region].present?
#region = params[:region]
#assigned = Call.where(region_id: params[:region][:area]).assigned_calls.until_end_of_day
#unassigned = Call.where(region_id: params[:region][:area]).unassigned_calls.until_end_of_day
else
#assigned = Call.assigned_calls.until_end_of_day
#unassigned = Call.unassigned_calls.until_end_of_day
end
end
Now your #region instance variable will be available in your index.js.erb
where you can pass it to other partials you are trying to render.
index.js.erb
$('#active').html("<%= escape_javascript render :partial => 'calls/assigned_calls', :locals => { :assigned_calls => #assigned, :region => #region } %>");
$('#inactive').html("<%= escape_javascript render :partial => 'calls/unassigned_calls', :locals => { :unassigned_calls => #unassigned, :region => #region } %>");
_assigned_calls.html.erb
<%= form_tag calls_path, :method => 'get' do %>
<%= select_tag "region[area]", options_from_collection_for_select(Region.order(:area), :id, :area, selected: region.try(:[], :area)), prompt: "Choose Region" %>
<%= submit_tag "Select", :name => nil, :class => 'btn' %>
<% end %>
Also, I think that better practice in your index.html.erb script tag
is to do it like this:
<script>
$(document).ready(function() {
setInterval(function () {
$.ajax({
url: 'calls_path',
type: "GET",
data: { "region": '<%= #region.html_safe %>' }
});
}, 5000);
});
</script>
Please test this out if you're interested and get back to me :)

link_to no route matches only after AJAX create of a post

Basically every time I create a post with AJAX, it won't render the new post because of this line:
<%= link_to "promote", vote_scribble_path(:scribble_id => scribble.id, :vote => true), remote: true, method: :post%>
THE LINK ABOVE ACTUALLY WORKS, it just prevents ajax render of newly created post.
here is the error that i get when trying to create new post with AJAX, it does actually create the post and it would render new post without the line above. After refresh of a page the new post with a working link appear.
Rendered scribbles/_scribbles.html.erb (18.9ms)
Rendered scribbles/create.js.erb (19.7ms)
Completed 500 Internal Server Error in 48ms
ActionController::RoutingError - No route matches {:action=>"vote", :controller=>"scribbles", :scribble_id=>155, :vote=>true}:
Here is the full code in action:
create.js.erb updates posts list after create
/*Replace the html of the div post_lists with the updated new one*/
$("#posts_list").html("<%= escape_javascript( render(:partial => "scribbles/scribbles") ) %>");
feedlist.html does render all of the posts
<div id="posts_list">
<%=render :partial => 'scribbles/scribbles', :locals => {:scribbles => #scribbles}%>
</div>
scribbles/_scribbles.html that link_to single line prevents ajax render. but it works.
<% #scribbles.each do |scribble| %>
<%= link_to "promote", vote_scribble_path(:scribble_id => scribble.id, :vote => true), remote: true, method: :post%>
<%end%>
even something like this gives me an error
<%= link_to "promote", vote_scribble_path()%>
vote_scribble_path(:scribble_id => scribble.id, :vote => true), remote: true, method: :post, :put,:get %> tried them all still same error
THE LINK WORKS IT JUST DOESN'T RENDER after AJAX CREATE, after page refresh everything is fine. any ideas why ?
resources :scribbles do
member do
post 'vote'
end
end
scribble_controller.rb
def vote
#scribble = Scribble.find(params[:scribble_id])
#vote = params[:vote]
if #vote == "true"
#v = :up
current_user.vote(#scribble, :direction => #v)
else
current_user.unvote_for(#scribble)
end
respond_to do |format|
format.js{}
end
end
You should be passing id instead of scribble_id in your link.
<%= link_to "promote", vote_scribble_path(:id => scribble.id, :vote => true), remote: true, method: :post%>
because as per your defined routes, the generated route for vote action would be:
vote_scribble POST /scribbles/:id/vote(.:format) scribbles#vote
which you can check by running rake routes.
As you can see vote_scribble_path is expecting an id placeholder and not a scribble_id which is why you receive the error as Rails cannot find a matching route in your application for scribbles#vote action with placeholder :scribble_id.

text field with dropdown in rails

I'm trying to build a form field that can either accept a text entry, or select an option from a dropdown. In rails, the autocomplete plugin is close to what I need, except I want the dropdown to be available before the user types anything in the text field. Is there an example of this out there somewhere?
thx for the help,
-C
I have used this code on a view to select a date or enter a name (I hope you read HAML):
%center
- form_remote_tag :update => 'filter_counts', :url => { :action => 'name_filter', :controller => 'dictated_exams', :method => :post } do
Please enter part of a name ('%' is the wildcard character):
= text_field_tag 'search', nil, :maxlength => 15, :size => 15
= submit_tag 'Search'
%b OR
pick the exam date:
= calendar_date_select_tag "date", Date.today, :time => false, :valid_date_check => "date < (new Date()).stripTime()"
= image_tag "spinner.gif", :align => "absmiddle", :border => 0, :id => "spinner", :style => "display: none;"
= observe_field :date, :with => :date, :frequency => 1, :url => {:action => 'filter_widget', :controller => 'dictated_exams', :method => :post }, :update => :filter_counts, :before => "Element.show('spinner')", :success => "Element.hide('spinner')"
On the other hand, maybe you're just looking for this:
Rails' observe_form method
Basically, the question is : do you need to have those two methods of entry in a single form, or can they be separate? If so, you can also watch them separately.

Categories