Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: "head :ok" interpreted as "ajax:error" [duplicate]

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!

like image 320
Railsana Avatar asked Sep 13 '12 13:09

Railsana


1 Answers

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.

like image 107
chris finne Avatar answered Sep 27 '22 02:09

chris finne