JOSEMAFUEN JOSEMAFUEN - 8 months ago 62
CoffeeScript Question

Rails controller not calling Javascript function

I need one of my Rails controllers to call a Javascript (Coffeescript) function after create in order to pass the id of the new object created. The problem is that the function is never called.

Here's the controller comments_controller.rb:

class CommentsController < ApplicationController
def create
newcomment = Comment.create!(comment: params[:comment], user_id: current_user.id, rutina_id: params[:id])
respond_to do |format|
format.js { render :js => "create_comment(" + newcomment.id.to_s + ");" }
end
end
...


And my CoffeeScript file rutinas.js.coffee:

$ ->
$('#dias').change ->
...

$('#diasedit').change ->
...

$('[id^="arrowUp"]').click ->
...

$('[id^="arrowDown"]').click ->
...

$('[id^="eliminar_com_"]').click ->
...

$('[id^="editar_com_"]').click ->
...

create_comment = (id) ->
console.log(id)
newComment = $('#com_model').clone();
newComment.removeClass('hidden');
newComment.find("td#content_com_model").html($('#comment').val());

today = new Date();
dd = today.getDate();
mm = today.getMonth()+1;
yyyy = today.getFullYear();
if(dd<10)
dd = '0'+dd
if(mm<10)
mm = '0'+mm
today = yyyy + '-' + mm + '-' + dd;
newComment.find("small#date_com_model").html(today);

newComment.find("small#date_com_model")

newComment.insertAfter($('#com_model'))


$('#printBtn').click ->
...


if document.getElementById("rutinas-list") != null
i = 0
while i < document.getElementById("rutinas-list").childElementCount
i += 1
do(i) ->
...

cambia_voto =(element, cambio) ->
...


$("#rutina_privacy_lvl").change ->
...


The newcomment is successfully created and newcomment.id.to_s contains the right value, I've checked it, but console.log(id) is never reached.

UPDATE

remote: true
is set in the form. In fact, i've tested

respond_to do |format|
format.js {
logger.debug "create_comment(" + newcomment.id.to_s + ");"
render :js => "create_comment(" + newcomment.id.to_s + ");"
}
end


And
create_comment(41);
is correctly logged in ruby's terminal

Answer Source

Following code from controller will execute when the request to action create is a JS request:

format.js { render :js => "create_comment(" + newcomment.id.to_s + ");" }

If you are using AJAX to send this request, then a possible mistake could be wrong value of dataType parameter. You need it set to "script" to make this JS work.

And if you are not calling the AJAX manually (using remote: true), then try writing this JS code in a .js.erb template.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download