Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>GearHead is correct, except that the jQuery parser is actually smart enough now to treat an empty string response as null and not attempt to parse it.</p> <p>However if you have calls that will sometimes receive json and sometimes receive a <code>head</code> response, and you do not have access to the server or do not want to change all your <code>head</code> calls, you can do this alternate solution:</p> <p>The problem is that Rails sends a single space as an empty response when you use <code>head</code> (see here: <a href="https://stackoverflow.com/questions/3351247/how-to-return-truly-empty-body-in-rails-i-e-content-length-0">How to return truly empty body in rails? i.e. content-length 0</a>)</p> <p>The relevant parts of the jQuery parseJSON function look like this at the time of this writing:</p> <pre><code>parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON &amp;&amp; window.JSON.parse ) { return window.JSON.parse( data ); } </code></pre> <p>As you can see, jQuery is testing whether the data is an empty string <em>before</em> trimming it. It then tries to <code>JSON.parse("")</code> which you can see in your console results in an error, triggering the ajax error callback via a <code>catch</code> statement.</p> <p>There is a simple fix. jQuery allows you to use converters when one data type is requested and a different one is returned. See here for more details: <a href="http://api.jquery.com/extending-ajax/" rel="nofollow noreferrer">http://api.jquery.com/extending-ajax/</a></p> <p>Since the rails <code>head</code> response renders as text, you can simply define a text to json converter that will trim the response prior to attempting to parse it. Just add this snippet:</p> <pre><code>// deal with rails ' ' empty response jQuery.ajaxSetup({ converters: { "text json": function (response) { jQuery.parseJSON($.trim(response)) } } }) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload