Rails, jQuery, .js.erb files, JS not executed by the browser - javascript

I'm trying to use jQuery, and everything has been great, until now, when I'm trying to render a partial and append it to a div. Here is how I have it set up:
I have an action that responds to js:
def index
#objects = Object.find(:all)
respond_to do |format|
format.js
end
end
And a template called index.js.erb with some javascript in it:
alert("hello world");
Firebug returns a "text/javascript" response containing:
alert("hello world");
But the alert window does not appear, nor does any other JavaScript work. I checked out http://railscasts.com/episodes/136-jquery
And am more or less following along. I tried several other things, like using .rjs instead of .erb and putting this in my template:
page.alert("hello world");
but I get the same exact result, and the browser never executes the JS.
Anyone know why the JavaScript isn't being executed?
I'm running Rails 2.3.4.

You have to call it from your view or it will never be executed.
an example controller:
def index
#objects = Object.find(:all)
respond_to do |format|
format.js{
render :text => "alert('hello')"
}
end
end
and an index.html.erb with:
<script type="text/javascript">
$(function(){
$.ajax({ url: '/controller', type: 'get', dataType:'script' });
});
</script>
replace '/controller' with the actual url that executes that controller's index action, by default for PostsController it will be '/posts' and so on...
if you like rjs you delete the {} and everithing in it in the controller and create an index.js.erb or index.rjs with:
page.alert("hello world")
or:
page << "hello world"

Related

js.erb not executing javascript but is processed rails

I'm trying to get my pagination working with Ajax, using either will_paginate or kaminari.
When I hit pagination link my log says
Processing by Instructor::FullDashboardController#pupil_leads as JS
and
Rendered instructor/full_dashboard/pupil_leads.js.erb within layouts/main (0.1ms)
But the js has no effect. So to test it I wrote
console.log("Hello");
<%logger.debug "This is the js file"%>
alert('Hello Rails');
In the js.erb file, in my log I see This is the js file as expected, but there is nothing in js console in my browser and the alert doesn't show. So I know the file is being processed, as my logger.debug works but there is no js.
How can I further troubleshoot this?
Rails 4.1
Ruby 2.1
Full Dash Controller
class Instructor::FullDashboardController < ApplicationController
layout 'main'
...
def pupil_leads
#ivar = Model.where("something = ?", some_object.id).order("created_at desc").page(params[:page]).per(10)
respond_to do |f|
f.js { render :content_type => 'text/javascript' }
f.html
end
end
Add layout: false option to the render block:
def pupil_leads
# some code here
respond_to do |f|
f.js { render layout: false, content_type: 'text/javascript' }
f.html
end
end
For some reason Rails don't recognize request as xhr, I also watched that the views extension (.erb.html or .slim) must be specified in full.

Ajax success callback in ruby on rails

Hi want to implement ajax in my ruby on rails tutorials and the controller will return an object on handling the ajax request. I dont know to handle the response in my javascript file.
I want to update some div based on object returned in javascript file.
Here is what I have written in my showcomments.js.erb
$('.show_comment').bind('ajax:success', function() {
$(this).closest('tr')="Something here from the object returned");
});
My link where ajax call is called is via this line of code
<td><%= link_to 'Show Comment', :action => 'showcomment' , :id =>article, :remote => true ,:class=>'show_comment' %></td>
My controller action where this request is handled is like this
def showcomment
#article = Article.find(params[:article_id])
#comment = #article.comments.find(params[:id])
respond_to do |format|
format.js{ render :nothing => true }
end
end
How can this be done?
I just wanted to try and expand on the other answers a little bit.
In rails when you add :remote => true to a link it essentially takes care of the first part of a jquery ajax call. That's why you don't need bind.(ajax:success, function(){ #
do stuff here });
This is a typical jquery ajax call
$.ajax({
url: "test.html",
type: "POST"
}).done(function() {
$( this ).addClass( "done" );
});
Rails takes care of the first part, up to the .done callback. So anything in your javascript erb template is put in the callback like this
.done(function() {
#your showcomments.js.erb file is inserted here
});
To render the showcomments.js.erb template from the controller just do this
def showcomment
#article = Article.find(params[:article_id])
#comment = #article.comments.find(params[:id])
respond_to do |format|
format.js
end
end
You don't need anything after format.js because the default rails action at that point is to render a js template with the same name as the action, in this case it's showcomment.js.erb.
Now you know when that link is clicked it will go straight to rendering that showcomment template , and any javascript in there will be run instantly. Rails makes using ajax very simple. I hope that helps.
change showcomment to this:
def showcomment
#article = Article.find(params[:article_id])
#comment = #article.comments.find(params[:id])
respond_to { |format| format.js }
end
In showcomments.js.erb you can access both objects #article and #comment.
A sample use is as below:
$('#yourdiv').html('<%= #article.name %>');
You render nothing when responding to js format. So code in showcomments.js.erb isn't evaluated. Remove { render :nothing => true } in controller and do whatever you want in showcomments.js.erb. BTW you don't need ajax:success event. It is the end of request already.
showcomments.js.erb
$('.show_comment').closest('tr').html("<%= # you may render partial here or whatever %>");

Rails 4 respond_to javascript

I have a simple PagesController with a 'homepage' method.
I just want the method to respond to my homepage.js.erb template file which is containing a simple console.log("Hello World!");
So i wrote respond_to do |format|
format.js
format.html
end
in my homepage method but it does nothing. ( no hello world in my chrome console ).
If i remove the format.html rails throw me this error "ActionController::UnknownFormat".
Is it a problem with turbolinks? how can i do?
Thanks JD
Turbolinks sends request as Html, So the js file wont get rendered but HTML one and on Client side turbolinks just replaces body with new content and updates URL.
If you want to render you js.erb file then you need to initiate js request not html. just write remote true in link_to.
Example
= link_to 'XYZ', url, :remote => true
Or if you want to execute js code on browser for HTML request then you need to write your JavaScript code inside you HTML file(format.html)
Example:
javascript:
console.log("Hello World!");

Rails update.js.erb not executing javascript

I am building a form in rails that will edit an existing question via ajax.
After the form is submitted and the question has been updated, the update method in the controller renders update.js.erb, which will hide the form again.
My problem is that the javascript code in update.js.erb is not executing at all.
I know that the file is rendering because it shows up in the server output, and when I put a
<% raise params %>
into it, it works.
However, even the simplest
alert('hello');
has no effect in the same file.
I've ruled out javascript and jquery configuration issues because the same code works perfectly in my edit.js.erb file. It's just not working in update.js.erb.
What am I missing?
Edit:
Firebug shows no errors. Here is the response in firebug's network panel:
alert('hello');
$('#question_body').replaceWith('<h4><p>jhsdfjhdsb k jdfs j fjfhds <strong>jfshaflksd;hf sdldfs l fdsalkhdfskhdfs</strong>;fd lfdksh hfdjaadfhsjladfhsjadfs ;df sjldfsj dfas hafdsj fdas ;ldfas ldfs df dl;hdf fdh ;fdj ;lfads</p></h4>');
def update
Edit 2:
This is the controller action:
def update
respond_to do |format|
if #question.update_attributes(params[:question])
format.html { redirect_to #question, :flash => { :success => 'Question was successfully updated.' } }
format.json { head :no_content }
format.js {}
else
format.html { render action: "edit" }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
In your $.ajax call make sure to set the dataType option to "script" otherwise the response could be interpreted in other ways and thus not executed as JS.
Do you work with haml, or html.erb? If the former, then this might be the solution:
respond_to do |format|
...
format.js {render layout: false}
end
I had the exact same problem, found this question early on, took another hour or so of Googling to find this question on StackOverflow that led me to it: jQuery + Ajax + Haml. js.erb files not firing
In your update.js.erb file you need to escape javascript wherever you execute ruby code.
$('.container').empty().append('<%=
escape_javascript(
render 'update'
)
%>')
This is what solved it for me ...
This issue isn't just because of Controller side. It is also can be in the View side which is you didn't clarify the data-type of your post request.
Make sure in your console that the request is treated as JS.
Reference: Similar issue
I ran into the same issue and found this page. I tried methods listed here but found no luck. While later the following method solve my issue.
My originally code was:
$('#html_id').html('<%=#ruby_variable%>');
And I updated it to:
$('#html_id').html('<%=raw #ruby_variable.to_json%>');
Now it works as expected.
Found out what it is! 😊 (solution for rails 4)
If you have in your ajax call parameters that are not in your permitted list, the record gets saved, you get no error messages about the 'not permitted' parameters, but the update.js.erb won't run - even though your terminal will feed back 'Rendered update.js.erb etc'
If the extra parameter is an attribute in your model, just permit it.
The simplest way to permit non model parameter is to add in your model:
attr_accessor :paramKeyTroublesome
Then you can also permit it in the controller.
in the $ajax call, data needs to be hashed up properly:
data: {model_name: {paramKey1: value, paramKeyTroublesome: value}}
One more problem to be aware of is an error in your update.js file. Nothing will execute if there are any syntax errors. You can check this by going to your browser inspector and enabling Log XMLHttpRequests Then reviewing the output js file.

Ruby on Rails + Ajax

I am trying to update a div in my rails application. Iam just learning ROR. So Its a learning stage for me.Please find the code.
In view page...
<%= javascript_tag do %>
jQuery(function($)
{
$("#tabs4").click(function()
{
$.ajax(
{
url:'/spaces/showcal',
type:'GET'
});
});
});
<% end %>
In spaces controller..
def showcal
respond_to do |format|
format.html
{
render (:update) { |page|
page.replace_html 'tab4', :partial => 'spaces/showcal'
}}
end
end
What am I doing wrong here.. Please help
I also have a partials page (_showcal)which has some text to display into that div.
When using ajax, a good way to debug this kind of thing is see what response the server returns. If it looks good, then you know your javascript code needs to change to get it working, if it looks wrong, then fix the server side code first.
Here's how i would do it:
def showcal
render :layout => false
end
#showcal.html.erb
<%= render :partial => "spaces/showcal" %>
Your js block:
jQuery(function($)
{
$("#tabs4").click(function()
{
$.ajax({
url:'/spaces/showcal',
type:'GET',
success: function(data)
{
$('#tab4').html(data);
}
});
});
});
I generally prefer using javascript as supposed to rails built in code when it comes to replacing and using content with ajax. I have to admit, because of this, I'm not sure if your update action was mostly correct or not. The page.replace_html should work if you're using the prototype helpers. The only thing is because you are doing an ajax request to achieve it and the resulting body would contain that code, and it would not execute on your current dom. So i think that was probably executing, but because it's on a separate page response, it didnt do anything.
Give my suggestions a try, and let me know how it goes. Sorry that my answer is a bit hazy.
You should request /spaces/showcal.js and react to format.js.
I never worked with $.ajax, you might need to set additional parameters there. With script.aculo.us, something like this works:
new Ajax.Request('/tasks/#{task.id}.js',
{asynchronous:true, evalScripts:true, method:'get'});

Categories