Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Action without View

I have what I think is a very simple problem. I'm coming from a PhP background, and used to do this all the time, so I may be looking at this the wrong way.

I am trying to create an ajax handler in RoR. When the user clicks a button, javascript fires off a POST, and gives the user feedback using the "success:" parameter of jQuery's ajax function.

The problem is, RoR is trying to load a view for the ajax handler, when I really just need a few lines in the controller to do the database work, and echo out a status code that will be interpreted by the user's javascript.

This is all just a mailchimp subscribe holding page, so I am only using the 'home' controller.

My Routes;

map.root :controller => 'home'
map.connect '/mcsubscribe', :controller => 'home', :action => 'mcsubscribe'

My Home Controller;

class HomeController < ApplicationController
  def index
    # no content
  end
  def mcsubscribe
    print params[:email]
  end
end

And my testing javascript, just so you understand what's going on;

function mcSubscribe() {
    var email = jQuery("#signup_input_email").val();
    jQuery.ajax({
        type: "POST",
        url: "http://domain.com/mcsubscribe",
        data: "email=" + email,
        cache: false,
        success: function(result) {
            alert(result);
        }
    });
}

I thought this would be a common problem, but I've googled around and only managed to find suggestions to redirect, as the user will never visit the /mcsubscribe page, that doesn't seem appropriate.

like image 487
lynks Avatar asked Mar 02 '12 12:03

lynks


3 Answers

In Rails 5 you need to use 'plain':

render plain: params[:email]
like image 68
HectorPerez Avatar answered Oct 12 '22 22:10

HectorPerez


Have a look at http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

You might need render :nothing => true

EDIT: misread your question, render :text => "yourtext" should fit your needs

like image 23
macsniper Avatar answered Oct 13 '22 00:10

macsniper


Using

print params[:email]

will just print that value to the application logs, not into the response.

You want this:

render :text => params[:email]
like image 11
Koraktor Avatar answered Oct 12 '22 23:10

Koraktor