Rectangle 27 84

redirect_to(:controller => 'jobs', :action => 'index')

with this:

render :js => "window.location = '/jobs/index'"

don't hardcode urls in a controller...

but the flash doesn't work, does it?

render :js => "window.location = '#{jobs_path}'"

It works, but wouldn't it be a lot better to pass back the redirect location with an actual json success message and do the redirecting on the front end?

Isn't jobs_path basically as rigid as the URL? If the URL changes, so would the name of the route, unless you are being extra careful. Another alternative would be render js: "window.location = '#{polymorphic_path(@job.class)}'" and use the calculated resourceful route based on the Job model. This only works if your routes are resourceful and use standard naming conventions that line up with your models. (Or if you specify model_name on your models so that they generate the right route names.)

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 84

redirect_to(:controller => 'jobs', :action => 'index')

with this:

render :js => "window.location = '/jobs/index'"

don't hardcode urls in a controller...

but the flash doesn't work, does it?

render :js => "window.location = '#{jobs_path}'"

It works, but wouldn't it be a lot better to pass back the redirect location with an actual json success message and do the redirecting on the front end?

Isn't jobs_path basically as rigid as the URL? If the URL changes, so would the name of the route, unless you are being extra careful. Another alternative would be render js: "window.location = '#{polymorphic_path(@job.class)}'" and use the calculated resourceful route based on the Job model. This only works if your routes are resourceful and use standard naming conventions that line up with your models. (Or if you specify model_name on your models so that they generate the right route names.)

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 49

There is very easy way to keep the flash for the next request. In your controller do something like

flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"

The flash.keep will make sure the flash is kept for the next request. So when the root_path is rendered, it will show the given flash message. Rails is awesome :)

thanks! had no idea about flash.keep

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 49

There is very easy way to keep the flash for the next request. In your controller do something like

flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"

The flash.keep will make sure the flash is kept for the next request. So when the root_path is rendered, it will show the given flash message. Rails is awesome :)

thanks! had no idea about flash.keep

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 26

render js: "window.location.pathname='#{jobs_path}'"
render js: "window.location.pathname = #{jobs_path.to_json}"

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 26

render js: "window.location.pathname='#{jobs_path}'"
render js: "window.location.pathname = #{jobs_path.to_json}"

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 22

In one of my apps, i use JSON to carry on the redirect and flash message data. It would look something like this:

class AccessController < ApplicationController
  ...
  def attempt_login
    ...
    if authorized_user
      if request.xhr?
        render :json => {
          :location => url_for(:controller => 'jobs', :action => 'index'),
          :flash => {:notice => "Hello #{authorized_user.name}."}
        }
      else
        redirect_to(:controller => 'jobs', :action => 'index')
      end
    else
      # Render login screen with 422 error code
      render :login, :status => :unprocessable_entity
    end
  end
end

And simple jQuery example would be:

$.ajax({
  ...
  type: 'json',
  success: functon(data) {
    data = $.parseJSON(data);
    if (data.location) {
      window.location.href = data.location;
    }
    if (data.flash && data.flash.notice) {
      // Maybe display flash message, etc.
    }
  },
  error: function() {
    // If login fails, sending 422 error code sends you here.
  }
})

Lots of good information here. Good and proper use of the render :location, of the :status option, and the xhr? check. As more web applications adopt APIs to serve mobile apps and the such, I hope to see things in this post become more standardized. Definitely have my upvote. Great Answer

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 22

In one of my apps, i use JSON to carry on the redirect and flash message data. It would look something like this:

class AccessController < ApplicationController
  ...
  def attempt_login
    ...
    if authorized_user
      if request.xhr?
        render :json => {
          :location => url_for(:controller => 'jobs', :action => 'index'),
          :flash => {:notice => "Hello #{authorized_user.name}."}
        }
      else
        redirect_to(:controller => 'jobs', :action => 'index')
      end
    else
      # Render login screen with 422 error code
      render :login, :status => :unprocessable_entity
    end
  end
end

And simple jQuery example would be:

$.ajax({
  ...
  type: 'json',
  success: functon(data) {
    data = $.parseJSON(data);
    if (data.location) {
      window.location.href = data.location;
    }
    if (data.flash && data.flash.notice) {
      // Maybe display flash message, etc.
    }
  },
  error: function() {
    // If login fails, sending 422 error code sends you here.
  }
})

Lots of good information here. Good and proper use of the render :location, of the :status option, and the xhr? check. As more web applications adopt APIs to serve mobile apps and the such, I hope to see things in this post become more standardized. Definitely have my upvote. Great Answer

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 15

Combining the best of all answers:

...
if request.xhr?
  flash[:notice] = "Hello #{authorized_user.name}."
  flash.keep(:notice) # Keep flash notice around for the redirect.
  render :js => "window.location = #{jobs_path.to_json}"
else
...

Thanks for your answer, I used it. However, now for the testing, when I try to request this action as JS, it raises a CORS warning : ActionController::InvalidCrossOriginRequest. Do you have any idea of how to integrate this in tests ?

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 15

Combining the best of all answers:

...
if request.xhr?
  flash[:notice] = "Hello #{authorized_user.name}."
  flash.keep(:notice) # Keep flash notice around for the redirect.
  render :js => "window.location = #{jobs_path.to_json}"
else
...

Thanks for your answer, I used it. However, now for the testing, when I try to request this action as JS, it raises a CORS warning : ActionController::InvalidCrossOriginRequest. Do you have any idea of how to integrate this in tests ?

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 1

def redirect_to(options = {}, response_status = {})
  super(options, response_status)
  if request.xhr?
    # empty to prevent render duplication exception
    self.status = nil
    self.response_body = nil
    path = location
    self.location = nil

    render :js => "window.location = #{path.to_json}"
  end
end

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 1

def redirect_to(options = {}, response_status = {})
  super(options, response_status)
  if request.xhr?
    # empty to prevent render duplication exception
    self.status = nil
    self.response_body = nil
    path = location
    self.location = nil

    render :js => "window.location = #{path.to_json}"
  end
end

Rails 3: How to "redirect_to" in Ajax call? - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 redirect
Rectangle 27 5

The web browser is expecting some javascript to be executed after the ajax has been called. Your code should work when javascript is disabled in the browser.

In the add_new_message method you should add:

respond_to do |format|
  format.html { redirect_to(:action => 'index') }
  format.js
end
window.location = '<%= forums_path %>'; //or whatever other path

Although both the HTML and javascript do the same thing. Why is the ajax needed in the first place?

But then how to you render error and notice messages on the redirected_to page?

@EricSteen Use the flash hash, e.g. flash[:error] = "Oh no!" and then in the controller action or view that is being redirected to you can access the message, e.g. The error was: <%= flash[:error] %>

Rails 3: "redirect_to" doesn't work well after Ajax call - Stack Overf...

ruby-on-rails ajax ruby-on-rails-3
Rectangle 27 34

The terminology in your question is a little confused. If are in a controller and you want to execute the code in another action method in another controller and render its template, you should redirect_to that action. Let's say the other controller is called ContractsController

redirect_to :controller => "contracts", :action => "show_home_page"

If you just want to use the view template from another method as the response from your action, you just need to prefix the name of the controller in the render parameter. This will not call the action, it will just use its template.

For example, if the template lives in the folder for the contracts controller.

render :action => "/contracts/show_home_page", :layout=> false

I think in this case you are actually talking about a partial, which would look like

render :partial => "/contracts/show_home_page"

However, what I see you grasping at here is that you actually want to call multiple action methods to render a single page. This is not how it works. You are going to have to set up the objects that the templates will reference in a single action. This is one reason most Rails developers put a lot of code in the models, so the setup isn't repeated all over the controllers.

In your page, create a function like this:

<script type="text/javascript" language="javascript">    
function load_categories() {
            <%= remote_function(:url => {:controller => "categories", :action => "list"},
                                  :update => "categories")%>
        };
</script>

If you call that in the onload even of your page, it will replace the div with id "categories" with the response from the action referenced.

such an amazingly thorough answer. I will digest this for a while and get back to you. Ultimately my hope was to create a set of "widget" like partials, which I could just plonk onto any view I like. The javascript method is something I hadn't even considered.

unfortunately remote_function no longer works as the prototype helper has been removed in rails 3.1 see we need workarounds like this

Rendering Partials From One Controller’s View to Another Controller’s ...

ruby-on-rails partial-views controllers
Rectangle 27 2

I'd be tempted to go for something like this in the controller:

def index
  @messages = Message.all
end

def add_new_message
  Message.create(:text => params[:new_message_area], ...)                 
  render js: %(window.location.pathname='#{messages_path}')
end

Rails 3: "redirect_to" doesn't work well after Ajax call - Stack Overf...

ruby-on-rails ajax ruby-on-rails-3
Rectangle 27 2

You are doing some AJAX call means, you must have invoked the AJAX part on radio button change

So I am assuming, you have done it using by radio button and the radio button name is 'choose_product'

You can add a hidden field in your view, where you can store your current date.

<div id='parentDiv'>
 <%= hidden_field_tag 'current_date', Time.now.strftime('%d-%m-%Y') %>
 Your radio button code
</div>

In the javascript add the following code. It is just a sample not complete solution.

$(document).ready(function(){
 var showProducts = function(){
  $("#parentDiv").on('click', "input[name='choose_product']", function(){
   var ajax_url = 'localhost:3000/dashboard/catalog';
   var url_param = '';

   switch($(this).val()){
    case 'creation_date':
     var param_date = $('#current_date').val();
     url_param = '?name=radio&date_creation=' + param_date;     
     break;
    case 'name':
     // Your code goes here
    default:
     //Your code goes here
   }

   // Here you will get the modified url dynamically
   ajax_url += url_param

   $.ajax({
    url: ajax_url,
    // your code goes here
   }); 
  });
 }

 showProducts();
});

Rails 3: update URL params with AJAX request - Stack Overflow

ruby-on-rails ajax ruby-on-rails-3 url params
Rectangle 27 5

destroy_user_session_path(@user) is sign out path for user, but it must requst with DELETE method. redirect_to method will tell broswer to request another path, but broswer just can request with GET method. So if you want to let user to sign out, you must set a sign out form with DELETE method or with AJAX request to let user sign out but not with redirect_to function.

sign_out @user

ruby on rails - How to devise destroy session and sign out from contro...

ruby-on-rails ruby ruby-on-rails-4 devise
Rectangle 27 36

There are several causes for this error, (relating to Rails 4). 1. Check <%= csrf_meta_tags %> present in page layout 2. check authenticity token is being sent with AJAX calls if using form_for helper with remote: true option.If not you can include the line <%= hidden_field_tag :authenticity_token, form_authenticity_token %> withing the form block. 3. If request is being sent from cached page, use fragment caching to exclude part of page that sends request e.g. button_to etc. otherwise token will be stale/invalid.

ruby on rails - ActionController::InvalidAuthenticityToken - Stack Ove...

ruby-on-rails
Rectangle 27 36

There are several causes for this error, (relating to Rails 4). 1. Check <%= csrf_meta_tags %> present in page layout 2. check authenticity token is being sent with AJAX calls if using form_for helper with remote: true option.If not you can include the line <%= hidden_field_tag :authenticity_token, form_authenticity_token %> withing the form block. 3. If request is being sent from cached page, use fragment caching to exclude part of page that sends request e.g. button_to etc. otherwise token will be stale/invalid.

ruby on rails - ActionController::InvalidAuthenticityToken - Stack Ove...

ruby-on-rails