Ruby on Rails script not being loaded - ruby-on-rails

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

Related

Rails 5.2: How do I use page specific JS scripts when using Turbolinks?

I am writing some exploratory javascript for a page. It includes the following line:
dashboard_settings.addEventListener('ajax:complete', function(){
...
I have placed the script just before the closing body tag.
I notice that when I navigate to the page, the JS works as I expect it to and there are no error messages in the console. However, when I navigate away from the page, an error message displays in the JS console:
Uncaught TypeError: Cannot read property 'addEventListener' of null
I understand that this is something to do with turbolinks. However, I am unsure how to go about avoiding it without turning turbolinks off.
Is there any way at all that I can specify that the script loads for the one page only?
I have tried the following without success:
<%= yield :page_scripts %>
<% content_for :page_scripts do %>
<script>
document.addEventListener('turbolinks:load', function(){
...
You can add the listener only if the element exists.
if (dashboard_settings)
dashboard_settings.addEventListener('ajax:complete', function(){...})
Or, if you wan't to add it only for a specific page, you could add a yield statement on your layout and only set it's content con the desired page
#layout
<html>
<body>
...
</body>
<%= yield(:after_body) -%>
</html>
#your view
<%= content_for :after_body do -%>
<script>
document.addEventListener('turbolinks:load', function(){
dashboard_settings.addEventListener('ajax:complete', function(){...})
})
</script>
<%- end -%>

Rails 4 - Moving js inline script inside View to JS file

I would like to move some js inline scripts I have on my homepage to a javascript file (in Assets) but there is some complexity due to variables.
home.html.erb
<div>
this is the homepage
</div>
<script>
<% #deal.deal_details.each_with_index do |popin, index| %>
<% index_plus_one = index + 1 %>
function loadInfoPopin() {
var msg;
msg = Messenger().post({
message: '<%= j render partial: "deals/info_popin/info_popin#{ popin['popin_id'] }",
locals: { popin: popin, index: index_plus_one } %>'
});
}
<% end %>
</script>
For the sake of information here is the format of the Deal's column/attribute 'deal_details' (it's a json attribute):
[{"popin_id":"4","text1":"qqq","text2":"sqsq","image1":"sqqs"},{"popin_id":"5","text1":"sqqs","video1":"s"}]
This is an example and you can have as many json block inside the array as possible.
deals/info_popin/info_popin5.html.erb (it's an example)
<div>
<p>cool image</p>
</div>
</div>
Now, how can I move the whole script or at least the function loadInfoPopin() to a javascript file (that is to say away from the view home.html.erb) ?
Thanks
How about moving the loadInfoPopin() function into a separate JS file and altering the function slightly to take in an argument for the html message?
function loadInfoPopin(html_message) {
Messenger().post({
message: html_message
});
Setup the html for the message within the loop before passing into and calling loadInfoPopin.
.js.erb is an option. This way the js files will be parsed before compiling. Not sure though it will work the way you want.
I would recommend to leave the variables in the layout as vars and moving only the static JS parts to the assets.

backbone.js + rails + firebug TypeError: this.model is undefined

Ok guys, I originally set out to render the users' NewView onto my root page. I have gotten to the point where I can see the form, but when I fill it out and click "Create User" I get this error:
TypeError: this.model is undefined
$(this.el).html(this.template(this.model.toJSON()));
Here is the relevant code:
index.html.erb
<div id="container">Loading...</div>
<script type="text/javascript">
$(function() {
window.newView = new Example.Views.Users.NewView({model: <%= #users.to_json.html_safe -%>,collection: new Example.Collections.UsersCollection()});
window.router = new Example.Routers.UsersRouter({users: <%= #users.to_json.html_safe -%>});
$('body').html(newView.render().$el);
Backbone.history.start();
});
</script>
Here is one question I posted today which has brought me to this question...reading the comments should be helpful!
ReferenceError: users is not defined rails + backbone + firebug
I have a feeling it has something to do with the fact that I created two windows? "window.newView" and "window.router".
There needs to be a router for Backbone.history.start() to work...correct? This is why I added the router line in the first place...because I was getting an error with Backbone.history.start().
I think this works, I passed "pushState: true" to the start method...does not throw any errors at least...and I can go through and sign up, show, and destroy a user...it doesnt redirect to the show page once the user is created when being created on the index page though.
<div id="container">Loading...</div>
<script type="text/javascript">
$(function() {
window.newView = new Example.Views.Users.NewView({model: <%= #users.to_json.html_safe -%>,collection: new Example.Collections.UsersCollection()});
window.router = new Example.Routers.UsersRouter({users: <%= #users.to_json.html_safe -%>});
$('body').html(newView.render().$el);
Backbone.history.start({pushState: true});
});
</script>
Please correct me if there is anything screwy with my fix.

How should I update the pagination links in an AJAX call?

So I've implemented AJAX pagination. The problem is that since the <%= paginate #videos %> code is not inside the partial that I render, the pagination links are not updated. What jQuery code should I use to update the pagination links?
Btw I tried $(".pagination").replaceWith('escape_javascript(<%= paginate #videos %>)');;
but i get this error: Uncaught SyntaxError: Unexpected token ILLEGAL
$(".pagination").replaceWith("escape_javascript(<%= paginate #videos %>)");; throws this error: Uncaught SyntaxError: Unexpected identifier
Here is the JS code the browser sees:
$(".pagination").replaceWith(" <nav class="pagination">
<span class="prev">
« Prev
</span>
<span class="page first">
1
</span>
<span class="page current">2</span>
<span class="page last">
3
</span>
<span class="next">
Next »
</span>
</nav>
");
Ideally, the new pagination links should be included in the HTML response of the ajax call. If that is not possible - presumably because the links reside elsewhere in the document, then I would suggest creating a context/link/URI/action/whatever (disclaimer: I'm not a ROR guy) which returns a JSON string, structured something like:
[{"data": "The HTML output"}, {"pageLinks": "pagination HTML"}]
and replace your ajax call with one which expects JSON as the return dataType. Then it should be easy, e.g.:
$.ajax({
url: 'theURL',
dataType: 'json',
success: function(json) {
$('.pagination').html(json.pageLinks);
$('#someDiv').html(json.data);
}
});
The problem looks to be the quotes in your use of replaceWith. You need to escape the characters of that string before trying to use it.
You have double quotes starting and ending your string argument in the replaceWith function but the string you are feeding it also has double quotes throughout that don't look to be escaped. Every time a double quote is encountered it is terminating the string and trying to parse the rest as javascript statements and not a string.
I know this is an old question, but I faced a simmilar problem using will_paginate gem, and I tryed a lot of complicated stuffs to update the pagination. However, I did it with a simple solution, that maybe can help someone else.
In summary, create a partial where you put the call to will_paginate helper inside a div, and after your ajax request, just render this partial again. For instance:
The _pagination.html.erb:
<div id="paginate">
<%= will_paginate #results %>
<div>
The your_template.js.erb (where #results should be available):
$('#paginate').html('j(render "pagination.html.erb")');
That should be enough.

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