2

Can anybody help me to resolve a small issue ?Actually I want to call some javascript functions from controller action method.I have written some code but it is not working.As I am totally new to ROR may be i have done mistake somewhere.Please check my below code snippets and modify these to run those successfully.

My code snippets are as follows.

views/users/index.html.erb:

<center>
    <h1>....Testing...</h1>
    <p>
        <a href="/users/browser"><button type="button">Check Browser</button></a>
    </p>
    <p>
        <a href="/users/time"><button type="button">Check Time</button></a>
    </p>
</center>

controller/users_controller.rb:

class UsersController < ApplicationController
    def index

    end
    def browser
        respond_to do |format|
            format.js{render :js => "my_browser();"}
        end
    end
    def time
        respond_to do |format|
            format.js{render :js => "my_time();"}
        end
    end
end

application.js:

function my_browser(){
    console.log('my browser function');
    var objOffsetVersion;
    if (objOffsetVersion=navigator.userAgent("chrome") != -1) {
        objOffsetVersion="chrome"
    };
    alert(objOffsetVersion) ;
}
function my_time(){
    var d = new Date();
    var currtime = d.getHours() * 100 + d.getMinutes();
    alert(currtime);
}

routes.rb

Jscript::Application.routes.draw do
  root :to => "users#index"
  get "users/browser" => "users#browser"
  get "users/time" => "users#time"
end

Please help me..Thanks in advance.

1

1 Answer 1

0

Try changing your links to use js format, as you are specifically telling your controller to handle js via format.js blocks:

<center>
  <h1>....Testing...</h1>
  <p>
      <a href="/users/browser.js"><button type="button">Check Browser</button></a>
  </p>
  <p>
    <a href="/users/time.js"><button type="button">Check Time</button></a>
  </p>
</center>

As an alternative you could tell rails to always render js in the controller for all formats:

class UsersController < ApplicationController
  def index
  end

  def browser
    render :js => "my_browser();"
  end

  def time
    render :js => "my_time();"
  end
end

Hope this provides some help.

Sign up to request clarification or add additional context in comments.

1 Comment

As per your instruction after editing your code i am getting only string(i.e-my_browser) as result.But my objective is call the my_browser function and execute the alert prompt within it.Any more suggestion..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.