I'm trying to replace the content of a div after clicking on a link using Rails 3, remote_link :remote => true
and jQuery.
So far, I've been able to get the controller render the correct partial while responding with a 200 HTTP code. I've set some callbacks to find the origin of the problem:
jQuery(function($) {
$("#follow-link").bind("ajax:before", function() {
console.log("ajax:before");
});
$("#follow-link").bind("ajax:success", function(data, status, xhr) {
console.log("ajax:success");
});
$("#follow-link").bind("ajax:complete", function() {
console.log("ajax:complete");
});
$("#follow-link").bind("ajax:error", function(xhr, status, error) {
console.log("ajax:error");
console.log(error);
});
});
While before
and complete
are triggered, success
is not and error
outputs "parsererror". The content I get when I inspect the response in Safari's developers tools is a simple string.
Why would it raise a parsererror? How can I get more information about what's causing this error?
I was also getting odd parsererror
s even though my remote links were correctly pointing to actions with :format => :js
and my controller actions were correctly using respond_to
to serve up JSON objects like:
respond_to do |format|
format.js do
render :json => {:something => "OK"}
end
end
The solution ended up being just dropping this line into my application.js
:
$.ajaxSettings.dataType = "json";
By default, it appeared that jQuery was trying to evaluate all responses as "script"
, which I guess means it was trying to execute it as code—? Dropping this line in once fixed the issue globally.
Instead of using the global $.ajaxSettings.dataType = 'json';
setting a cleaner solution is to add a data-type
attribute to the form element. The remote form event handlers will pass this through as the dataType to the jQuery AJAX call, e.g:
form_for @subject, :remote => true, :html => {'data-type' => 'json'}
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