Rendering a partial using ajax - ruby-on-rails

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>

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();

How to make asynchronous GET request on RAILS and only get view form (not whole body and headers)

I created a simple asynchronous jquery function on my rails app so I can print the response on a "display" div. But when I make the GET request to my rails url it responds the whole html: "body", "head" and "includes" as if it were a new page on a browser, so the resulting source is the following:
Before I push the button:
<html>
<head>
<title>Myapp1</title>
</head>
<body>
<button onclick="callPage()">Call</button>
<div id="display"></div>
</body>
<html>
After I push the button and the "display" div is filled with my response:
<html>
<head>
<title>Myapp1</title>
</head>
<body>
<button onclick="callPage()">Call</button>
<div id="display">
*<html>
<head>
<title>Myapp1</title>
</head>
<body>
-----Content of page user/1 which is the only thing I want to get.------
</body>
<html>*
</div>
</body>
My route to users on routes.rb (RUBY ON RAILS) working fine
resources :users
#get 'welcome/index'
match ':controller(/:action(/:id))', :via => :get
My Jquery GET callPage (working fine)
<script>
function callPage()
{
url="user/1";
div="display";
$.ajax({
type: "GET",
dataType: "text",
url: url,
success: function(msg){
if(parseInt(msg)!=0)
{
$("#"+div).html(msg);
}
}
}).setRequestHeader('X-CSRF-Token', AUTH_TOKEN);
}
</script>
The question is how do I prevent RAILS from printing out every html tag all over (body, heads,...) and get it to print only the view of the controller I want (in this case, users). ¿Is it a configuration somewhere or do I wave to trim this off somehow?
Thanks a million in advance for your time.
To only display the view you have to change your controller action to have render layout: false at the end. This will prevent the layout from rendering, leaving only the content in your view file.
For example:
class YourController < ApplicationController
def show
# bla bla
render 'your_show_view_name', layout: false
end
end
If you want all your controller actions to have this behavior you can put it right at the top
class YourController < ApplicationController
layout false
def show
# bla bla
end
end

Turbolinks, limit javascript to one page

I am using highlight.js and applying this code to initialise the syntax highlighting for my code snippets on a blog app.
The following code is on my index.html page :
<script>
$(document).on('ready page:load', function() {
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
});
</script>
A code snippet should look like this originally:
<pre><code>A
B</code></pre>
And after applying the new style it turns into this:
<pre><code class=" hljs">A
B</code></pre>
The problem is that when I try to edit one of those posts on the edit.html page, in the editor I get the stylized version instead of the plain one, which I do not want. I want the new styles to be applied only to the index page. How can I make that happen?
I should mention I have generated a scaffold with all the included views: index, new, edit etc.
Also I have the jquery-turbolinks gem installed.
The problem goes this way: I load index.html and I get highlighted code. I navigate to edit.html and get highlighted code. I refresh the edit.html page and lose the highlight (which is how it should be).
--------------------------------------------EDIT-------------------------------------
Tried this and it did not work:
in my aplication.html.erb:
<body data-action="<%= action_name %>" data-controller="<%= controller_name %>">
in my index.html.erb
<script>
var data = $('body').data();
if (data.controller === 'posts' && data.action != 'edit'){
$(document).on('ready page:load', function() {
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
});
};
</script>
<body data-action="<%= action_name %>" data-controller="<%= controller_name %>">
You can then read this in your script:
$(document).on('page:change', function(){
var data = $('body').data();
if (data.controller === 'foo' && data.action === 'bar'){
};
});

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.

How I Render A Html/JavaScript In Grails Controller?

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'

Resources