Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parser error when using jQuery-UJS for remote link_to in Rails 3 app: how can I debug this?

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?

like image 414
martini-bonanza Avatar asked May 22 '11 17:05

martini-bonanza


2 Answers

I was also getting odd parsererrors 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.

like image 178
Adam Florin Avatar answered Dec 30 '22 03:12

Adam Florin


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'}
like image 45
subblue Avatar answered Dec 30 '22 03:12

subblue