Yios
Yios

Reputation: 133

redirect_to from jquery in rails 4

While on a view, the user can use existing buttons to increase/decrease the quantity of the products in his cart.

When the cart has not products i want to navigate to another view. Since i am in jquery on the browser and already know where i want to go, I presume it doesnt make much sense to let the user proceed only to capture this situation later on on the controller/model.

Therefore, my question is how can i navigate to another view from within xxx.js.erb the rails-way?

UPDATE Thanks Зелёный for guiging me to the right direction

What worked for me was: $(location).attr('href','<%=j store_index_url %>');

Upvotes: 1

Views: 2355

Answers (3)

Yios
Yios

Reputation: 133

thanks <Зелёный> for guiding me to the right direction. I ended up using this:

 $(location).attr('href','<%=j store_index_url %>');

Upvotes: 0

Richard Peck
Richard Peck

Reputation: 76774

Validation

You'll have to do this:

#app/assets/javascripts/application.js
$(document).on("click", ".cart_button", function(){
   if( $(".cart_total").val() == "0" ){
      document.location.href = "/your/new/path";
   }else{
      //etc
   }
});

Ajax

A much better way to handle this will be with ajax

Specifically, you'll be sending requests to your cart_controller I presume. This means that if you want to manage the response in regards to the quantity of the cart, you'll be in a much stronger position if you use the built-in Rails js backend handling:

#app/controllers/cart_controller.rb
class CartController < ApplicationController
   def update
       @cart = ....
       respond_to do |format|
          format.js
          format.html
       end
   end
end

This will give you the ability to load the following:

#app/views/cart/update.js.erb
<% if @cart.total_quantity.zero? %>
  var new_path = "<%=j controller_path %">;
  document.location.href = new_path;
<% else %>
  // do something here
<% end %>

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You can redirect by Javascript try work aroud this example:

# xxx.js.erb
function() {
  var new_path = <%= @some_path_from_controller %>;
  document.location.href = new_path;
};

Read about document.location

Upvotes: 3

Related Questions