28

Possible Duplicate:
jquery doesn’t call success method on $.ajax for rails standard REST DELETE answer

I respond to a remote-link (data-remote="true" data-type="json") and output

format.json { head :ok }

in my Rails (3.2.6) controller, which creates this header:

Status Code:200 OK

...
Connection:keep-alive
Content-Length:1
Content-Type:application/json; charset=utf-8
Server:thin 1.4.1 codename Chromeo
Set-Cookie: ... path=/; HttpOnly
X-UA-Compatible:IE=Edge
...

In my JavaScript file ajax:complete is triggered and outputs 200 (data.status).

  $( '#myElement' ).on( 'ajax:complete', function( e, data ) {
    console.log( data.status );
  });

data looks like this:

 ...
 readyState: 4
 responseText: " "
 setRequestHeader: function ( name, value ) {...
 state: function () {...
 status: 200
 statusCode: function ( map ) {...
 statusText: "OK"
 ...

Looks pretty good to me...

The problem

Instead of ajax:success, jQuery (jquery-ujs) executes ajax:error and I have no idea why since no error is given.

I have looked into alot of discussions, but this way always seemed to be the solution, not the problem. Thank you for any help!

Community
  • 1
  • 1
Railsana
  • 1,813
  • 2
  • 21
  • 30

1 Answers1

44

Answered here.

jQuery is expecting a JSON response. "head :ok" has a single space for the response body, so jQuery fails to parse the JSON response so it still considers the 200 status code an error.

You can have Rails respond with head :no_content which has an empty body or a render :json=>true

This was discussed in Rails here.

The reason for the single space in head :ok in Rails is a workaround in an old Safari bug.

Community
  • 1
  • 1
chris finne
  • 2,321
  • 22
  • 17