This seems like it should be pretty straightforward, but its stumping
me. I have a small form that I am trying to submit using jquery that
is supposed to remove an association between to HABTM models. For the
sake of argument, the models are Course and Student.
respond_to do |format|
format.html { redirect_to edit_class_path(@class) }
format.js
end
end
# remove_student_from_class.js.erb
// reload the page
location.reload();
Everything works fine, except the HTML code is generated and not the
JS code in the respond_to block. I would expect the JS call to get
fired since I have the ':remote => true' line in there, but its always
the HTML and it generates the page. What am I overlooking?
Do you have anything pertinent/related/involved in the application.js
file? Try pulling that out as you could be having a failure in JS
that's causing grief. Also -- check your console in Firebug (or
whatever you're using) and see if errors are being thrown when the
page loads.
Nope, nothing in the application.js file. Checked the firebug output
and there is nothing. The JS is not even getting fired, which make no
sense because I have the ':remote => true' statement in there. It
even creates the 'data-remote' call in the HTML output (see below). I
thought that was the key to UJS in Rails3?
I'm sure you checked this but just in case... based on what you just
said, check to make sure you haven't disabled JS in your browser.
Put a "Hello World" script in Application.js
I'm using jQuery in Rails 3 with Ruby 1.9.2 and it's working fine:
I use <%= javascript_include_tag :default %> with :default defined as
Yep, Javascript is enabled, and working fine. Apparently, I have
stumped the brightest minds in the rails world That can only mean
one thing...i'm overlooking something very simple and I'll feel quite
dumb when the answer is presented to me
The problem appears to be the dataType of the Ajax request -- it is
requesting an HTML response rather than a script. I wonder if the
default has changed recently?
Anyway, calling
$.ajaxSetup({ dataType: 'script' });
at the top of your application.js or similar will change the default and
appears to restore the expected behaviour. You could also set the
data-type="script" attribute on your <form> or <a> tags.
The solution was to add a line of jQuery to set the proper request
header to handle Ajax calls. In my
app/views/layouts/application.html.erb, just add this after you include
the jQuery file: