Rails 3 Unobtrusive JavaScript - Handles JSON Response

I have a simple search form that looks something like this:

app / views / search / index.html.erb

<%= form_for @search, :as => :search, :remote => true, :url => {:action => "query"}, :html => {:id => 'search-form'} do |f| %> ... <% end % 

* application / controllers / search_controller.rb *

 def index @search = SearchCriteria.new end def query @search = SearchCriteria.new(params[:search]) unless @search.valid? respond_to do |format| format.json { render :json => {:error => 'validation failed'}, :status => 400 } end return end # otherwise, perform search... render :json => @results end 

public / javascript / application.js

 $(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); }); }) 

The problem is that when I endure 400 with an error in JSON, how can I get this 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, and not as JSON. The "ajax: success" handler seems to get the actual JSON data in the "data" parameter.

I am using Rails 3 + jQuery (UJS).

+4
source share
1 answer

You can use jQuery.parseJSON to turn xhr.responseText into a JSON object:

http://api.jquery.com/jQuery.parseJSON/

 console.log("error json: ", jQuery.parseJSON(xhr.responseText)); 
+6
source

Source: https://habr.com/ru/post/1343898/


All Articles