32

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
dmanaster
  • 579
  • 1
  • 6
  • 16
  • Checkout the response in firebug's network panel. What does it show? – Arjan Sep 21 '13 at 19:26
  • Added the response to the question. Thanks for taking a look. – dmanaster Sep 21 '13 at 19:46
  • show did you build the ajax into your form? If for instance you just call $.ajax(..) but do nothing with the response nothing will be executed, opposed to for instance using jQuerys getScript (http://api.jquery.com/jQuery.getScript/) – trueunlessfalse Sep 21 '13 at 20:28
  • It's built into the form via `:remote => true`. The form is submitting fine, and the changes are recording in the database. It's the javascript that is called after the update method calls update.js.erb that is not working. – dmanaster Sep 21 '13 at 20:49
  • post your update controller action – klaffenboeck Sep 21 '13 at 20:57
  • I just added the controller action to the question, but I do not believe that is the problem because update.js.erb is being rendered and rails code in the file such as `<% raise params %>` are working - it's just the javascript & jquery code in that file that are giving me headaches. – dmanaster Sep 21 '13 at 21:21
  • Did you escape the html in your javascript file? Try copy pasting your response and running it manuall in firebug console. Try to see if that gives any errors. – Arjan Sep 22 '13 at 20:45
  • The code works as intended when I paste it into the console. No errors. – dmanaster Sep 23 '13 at 00:21
  • Should this be a partial? ie. _update.js.erb – ezis Oct 10 '13 at 20:50
  • Have you ever found out? I have exactly the same problem - just with a create action. Also, if I run the ajax call via its 'own method', I have no problem. I think it must have something to do with RESTfulness and the actions create and update. I used to be able to do this with earlier rails versions. – Daniela Jul 16 '17 at 02:25

7 Answers7

55

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.

supermoogle
  • 1,207
  • 10
  • 7
  • 1
    perfect answer! incase some one needs to use it with `button_to` : `form: { "data-type" => "script" }` – simo Nov 21 '18 at 14:51
38

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

Community
  • 1
  • 1
rmatena
  • 466
  • 5
  • 10
  • 2
    ```{render layout: false}``` has wasted my 3 hours for same problem. After adding it, it works fine. Thaks – przbadu Apr 22 '14 at 12:49
  • After days of struggling, this worked for me :) Thanks – HermannHH Aug 18 '16 at 18:37
  • 1
    Works here too. But why do I need `render layout: false` here? I've already specified a layout at the top of the controller file. I've used the exact same pattern (submitting via `remote: true` and modifying the page in `create.js.erb`) in several places without ever using `render layout: false` before. – Sasgorilla Dec 03 '16 at 01:44
  • you are my hero – nilid May 28 '19 at 20:53
4

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 ...

Ricky Mason
  • 1,838
  • 6
  • 31
  • 60
2

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

Community
  • 1
  • 1
Hoang Le
  • 1,341
  • 14
  • 14
1

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.

wyncg
  • 53
  • 4
0

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}}
Daniela
  • 234
  • 2
  • 13
0

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.

Shadoath
  • 720
  • 1
  • 15
  • 31