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
Create the js. erb in the view folder itself with the same name as that of the action. In the view where some form is created which will be calling this action, make the request using :remote => true .
.js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the $('#business_submit'). click(...) in your application.
While RoR is a server side web development framework, JavaScript is a client side programming language. Therefore, you can easily use both of them within a single tech stack.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With