Sunday, May 19, 2024
100
rated 0 times [  104] [ 4]  / answers: 1 / hits: 18645  / 13 Years ago, tue, march 29, 2011, 12:00:00

When foo method of MyController is called via Ajax, it may return Javascript code like this:



class MyController < ApplicationController
def foo
render :js => alert('Hello');
end
end


Is that possible to do something similar to return a Javascript code when foo is called normally (not via Ajax) ? I would to do something like this:



class Job < ApplicationController
def edit
if user_type == 'demo'
[Here I would like to display a Javascript alert saying that
the job cannot be edited in demo mode. How would you do this?]
else
@job = Job.find(params[:id])
end
end
end

More From » ruby-on-rails

 Answers
19

short answer is : You can't.



When you render for :js, the calling code is a javascript framework which is aware that it requested js and will execute the returned code to make it take effect when the asychronous call executes it's onSuccess action.



When rendering for the default, the calling code is the browser which expects html it won't execute pure js.



What you can do is make your view return html with some javascript at the beginning with a window.onload() handler defined to make it display the alert. But you still have to return the html (if you don't want to display the data, make it redirect to the previous view template with a specific argument so the view will have the event handler)
(https://stackoverflow.com/questions/1033398/execute-javascript-when-page-has-fully-loaded)



You could also change the event handler which calls the edit action to display the alert even before the action is executed. to prevent a user from disabling js and getting over the alert, you need to still make the check on user_type and maybe simply redirect to the previous page.


[#93030] Sunday, March 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joseluispauld

Total Points: 13
Total Questions: 132
Total Answers: 98

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
;