Remotipart file upload giving NaN as response code

390 Views Asked by At

I am using remotipart to upload a file with ajax in my rails app. I am using the jquery-ujs Ajax "global" events ajax:success and ajax:error in my javascript to trigger code on success or failure. The problem is that the error callback is always firing and never the success.

I can see in the developer tools network tab that the request is returning a 200 OK status.

This is my form where the remote upload is triggered.

= form_tag({ action: 'import' }, html: { multipart: true },  class: 'csv_import_form', remote: true, data: { type: :json }) do

My controller processes the request as json and renders a json response:

def import
  render json: { some: 'sample json' }
end

and this is what the response body looks like as seen in developer tools:

<textarea data-type="application/json" data-status="200" data-statusText="OK">{"some":"sample json"}</textarea>

Remotipart wraps the response in a text area. Notice that it does include data-status="200"

Here is the javascript:

$(function() {

  $(document).on("ajax:success", ".csv_import_form", function(event, data, status, xhr)  {

    // does not get here

  }).on("ajax:error", ".csv_import_form", function(event, xhr, status, error) {
      console.log("status code: " + xhr.status);
      console.log("json: " + xhr.responseText);
      console.log("status text: " + xhr.statusText);
      console.log("status: " + status);
      console.log("error: " + error);
  });
});

This is what I see output in the console:

status code: NaN
json: {"some":"sample json"}
status text: OK
status: OK
error: OK

It seems the actual Textarea response is not being properly parsed. Even though it has data-status="200", it is being parsed as a NaN and thus invoking the error callback.

Has anyone seen this?

Using:

rails 4.0.13
remotipart 1.2.1
jquery 1.7.2

Thanks

1

There are 1 best solutions below

0
On

It turned out that even though I upgraded the remotipart gem to the latest version (1.2.1 at this time), the included javascript files had gotten out of date.

To fix I deleted:

app/assets/javascripts/jquery.remotipart.js

and

app/assets/javascripts/jquery.iframe-transport.js

and instead added

//= require jquery.remotipart

to my application.js file, and then it worked as expected.