How I Render A Html/JavaScript In Grails Controller? - grails

I have a controller code like this :
def test23() {
//params.id23 is been passed via ajax calls
def find = User.findByUsernameLike("${params.id23}")
println find
render """<script type="text/javascript"> alert("hi"); </script>"""
}
This code is called using jquery's ajax method. Well, it works well, that is , I get output printed on my console, but the render part is not working (I'm not getting the alert).
What I done is correct? Or anything else need to be passed to render those scripts?

try this instead:
render text: """<script type="text/javascript"> alert("hi"); </script>""",
contentType: 'js'
or possibly:
render text: """<script type="text/javascript"> alert("hi"); </script>""",
contentType: 'text/javascript'

Related

Ruby on Rails script not being loaded

In my ruby on rails application, I'm generating a view via an ajax call.
I'm using following piece of code.
$("#a_div_id").html("<%= escape_javascript(render 'index')%>");
And the view I'm trying to render is _index.html.erb:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
alert('first');
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
alert('second');
$scope.firstName = "John";
$scope.lastName = "Doe";
});
alert('third');
</script>
When I render the view, I'm getting only first and third messages. However, when I add this piece of code into dashboard.html.erb rather than rendering it via the ajax code, it perfectly works.
In the first case, I'm getting the following error.
angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=myApp&p1=Error%3A%2…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.8%2Fangular.min.js%3A20%3A274)
at angular.min.js:6
at angular.min.js:38
at n (angular.min.js:7)
at g (angular.min.js:37)
at eb (angular.min.js:41)
at c (angular.min.js:19)
at yc (angular.min.js:20)
at Zd (angular.min.js:19)
at HTMLDocument.<anonymous> (angular.min.js:294)
at fire (jquery.self-bd7ddd3….js?body=1:3233)
I'm be at my wits' end, I couln't decide what I'm missing,
Any suggestions,
Thanks.
​
Can you try without escape_javascript.
Also put a debugger like this, this will put a break point when chrome executes the js.
debugger;
$("#a_div_id").html("<%= render 'index' %>");
That would help you see what exactly jquery is trying to add as HTML.
If this doesn't work,
Probably you should take the js in script tag and put it in some method and call that method after you have added index to dom.
$("#a_div_id").html("<%= render 'index' %>");
myMethodToRenderAngular();

Need to pass parameter from partial render to a javascript function in .html.erb file?

I will post only the relevant snippet of the file
index.html.erb
<%= render "trace/outbound_message", error => #msg_error,:selector => "#ui-accordion-accordion-panel-3", :tab => "ui-id-1" %>
_outbound_message.html.erb
<% unless error.blank? %>
<%= error.html_safe %>
<script>
$(function() {
show_error(<% selector %>,<% tab %>);
});
</script>
<%end%>
But this function is not able to be called successfully, as I don't think js undersands the embedded ruby code. What is my quickest workaround? Do I have to call a js.erb file, and how do I pass parameters to & in it?
UPDATE
I changed the script to
<script>
alert("check-up");
$(function() {
show_error(<%= selector %>,<%= tab %>);
});
</script>
And even that alert is not being shown? Any ideas?
Use the ruby code in a block like:
In Ruby code:
v = "show_error(<%= selector %>,<%= tab %>);"
In javascript:
<script>
$(function() {
$(#{v});
});
</script>
I think the problem is you quotes ! You should have something like this
show_error(foo,bar);
and you need something like
show_error('foo','bar');
And don't forget to escape your JS :
show_error('<%= escape_javascript(#selector) %>', '<%= escape_javascript(#tab) %>');
How about this ?
<script>
alert("check-up");
$(function() {
show_error(<%= selector.to_json %>,<%= tab.to_json %>);
});
</script>
The to_json function will wrap your variable between quotes, that were missing.
I was playing around, and I figured it out.
<%= javascript_tag( "$(function() {show_error('#{selector}','#{tab}');});")%>
The javascript_tag played a vital role. You can't enclose it in ...
Btw #Saurabh - You were exceptionally close to the answer, no idea why somebody down-voted you.

Rendering a partial using ajax

It seems simple but my partial is not rendered in a view(dash.html.erb) using ajax.
routes.rb
match "users/dash" => "users#dash"
users controller
def dash
respond_to do |format|
format.js
end
end
dash.html.erb
<div id= "mydiv">This view is not shown using ajax.</div>
dash.js.erb
$('#mydiv').html('<%= raw escape_javascript render("cart_payment") %>');
My partial- _cart_payment.html.erb
<p>This is a partial.</p>
UPDATE:
users/index.html.erb
<script type= "text/javascript">
$.ajax({
url: "users/dash",
data: {
//params if needed
}
});
</script>
Please note that I am calling- users url in browser because ajax is called from here.
Is it not correct way or Am I missing something?
When you call the dash method remotely, it actually is executing the $('#mydiv').html... code. The problem is, your index.html.erb file has no <div id='mydiv'> to update in the first place.
If you replace your index.html.erb with this, it should work:
<div id='mydiv'></div>
<script type= "text/javascript">
$.ajax({
url: "users/dash",
data: {
//params if needed
}
});
</script>

Appear Select dynamic on change other select Rails

I have an error when making a dynamic select. My ajax doesn't work when I change my select.
This is the view code:
<%= select_tag 'cost', options_for_select(Cost.all.map { |c| ["#{c.types}", c.id] }),:id => "cost_select" %>
<script type="text/javascript">
$(document).ready(function(){
$("#cost_select").live('change',function(){
$.ajax({
url: "finances/cost_type",
type: "GET",
data: {'cost=' + $('#cost_select option:selected').value() },
})
});
});
</script>
Im my finances controller, I have this:
def cost_type
#places = Place.find_by_cost_id(params[:cost])
respond_with #places
end
I make the cost_type.js.erb file, and my response is in js.
My problem is when i change the select tag dont active no one action, how is the problem whit the code in my searchs i find this code working but what is the problem?
UPDATE:
my routes.rb contains:
get "finances/cost_type" => "finances#cost_type"
I solved my original question with the following:
$(document).ready(function(){
$("#cost_select").change(function(){
$.ajax({
url: "finances/cost_type",
type: "GET",
data: {cost: $("#cost_select option:selected").val() },
})
});
});
With this, I received a valid response (which I verified via firebug):
$("#cost_select").after("<select id="from_money" name="from_money"><option value="2">Luz</option></select>
");
However, the data isn't appearing in my view. I tried putting it in a different <div> but the <select> won't appear.
I don't know what is wrong, please provide me with any possible suggestions.
change your javascript to
$(document).ready(function(){
$("#cost_select").live('change',function(){
$.ajax({
url: "/finances/cost_type",
type: "GET",
data: { cost: $('#cost_select').val() }
})
});
});
the extra / before finances makes sure that you're using absolute paths. the data part is also wrong as pointed out in one of the comments but this is a cleaner version.

how to access javascript variable in rails view

Is there any way to access javasript variable inside the rails view.
I just set some value of javascript variable and want to access it in rails view.
Thanks
You have to understand that ruby code in your views gets executed on the server - before any javascript on the page gets a change to be executed.
That's why you cannot do stuff like this:
<script>
var js_var = 1;
</script>
<%= get_value_of_js_var_somehow %>
The other way round it works:
<script>
var js_var = <% generate_value_with_ruby %>;
do_something_in_javascript_with_js_var();
</script>
You can pass a javascript variable to rails using AJAX. For example if you want to pass the id for an user to a method in a rails controller from javascript you can execute the following code:
<script>
var id = 1;
<%= remote_function :url => {:controller=>'controller_name', :action=>'method_name'}, :with => "'user_id=' + id" %>
</script>
You will receive the variable through a POST request, as a parameter. You can access it using params[:user_id].
def method_name
if params[:user_id].exists?
u = User.where('id = ?', params[:user_id]).first
end
puts u.path
end
Hope I've answered your question.
If you have this Javascript variable in a higher piece of javascript (per se: the application.js), then you can always just reference it in the view.
#application.js
var someVar = "Hello World";
Then in your view (executed on the client), you could to...
<script type='text/javascript'>
alert(someVar);
</script>
I think we need more specific ellaboration if one of these three posts doesn't answer your question.
Suppose we are having script as follows
<script type="text/javascript">
var a="some value";
document.getElementById('tagid').innerHTML='<%= tag(:div,content_tag(:p,' " +a+ " '), :id=>' " +a+ " ', name=>"somename") %>';
</script>

Resources