title: Rails 3 Unobtrusive JavaScript - handle JSON response
body: <p>I have a simple search form that looks something like:</p>
  
  <p><em>app/views/search/index.html.erb</em></p>
  
  <pre><code>&lt;%= form_for @search, :as =&gt; :search, :remote =&gt; true, :url =&gt; {:action =&gt; "query"}, :html =&gt; {:id =&gt; 'search-form'} do |f| %&gt;
    ...
  &lt;% end %
  </code></pre>
  
  <p>*app/controllers/search_controller.rb*</p>
  
  <pre><code>def index
    @search = SearchCriteria.new
  end
  
  def query
    @search = SearchCriteria.new(params[:search])
  
    unless @search.valid?
      respond_to do |format|
        format.json { render :json =&gt; {:error =&gt; 'validation failed'}, :status =&gt; 400 }
      end
      return
    end
  
    # otherwise, perform search...
  
    render :json =&gt; @results
  end
  </code></pre>
  
  <p><em>public/javascripts/application.js</em></p>
  
  <pre><code>$(function() {
      $('search-form')
          .bind('ajax:success', function(e, data, status, xhr) {
              console.log("data=" + data);
          })
          .bind('ajax:error', function(e, xhr, status, error) {
              console.log("error json: " + xhr.responseText);
          });
  })
  </code></pre>
  
  <p>The problem I have is that when I render a 400 with an error in JSON, how can I get that JSON in the ajax:error handler? Using firebug I could see that the data/message seems to be stored in xhr.responseText as a String, not as JSON. The 'ajax:success' handler seems to get the actual JSON data in the 'data' parameter.</p>
  
  <p>I'm using Rails 3 + jQuery (UJS).</p>