Using respond_to ... format.json and jQuery Form Plugin by malsup Using respond_to ... format.json and jQuery Form Plugin by malsup json json

Using respond_to ... format.json and jQuery Form Plugin by malsup


Several things are needed to make jQuery Form plugin work for file uploads with a JSON response.In the javascript, the options for .ajaxForm should have:

dataType: 'json', // evaluate return as JSON

The browser needs to tell the Rails action to return content as JSON,one way to do this is add a hidden format input field in the file upload form template:

<%= hidden_field_tag 'format', 'json' %>

The Rails action will then run the format.json method inside the respond_to block.

In the server action

  • encapsulate JSON in a tag,.ajaxForm will unwrap the string and eval JSON correctly
  • set return content type to “text/html”, otherwise some browsers (Firefox) will try to download the return into a file.

e.g.

  respond_to do |format|    format.json {          render :json => "<textarea>#{data.to_json}</textarea>", :content_type => "text/html"    }  }


I did a workaround for this problem. I tested this solution only with Rails 3, but maybe it works also for the 2.3.x

The solution is very simple:

!#javascript$('form#my_form').live('submit',function(){  $(this).ajaxForm({ dataType: "script", success: processJson}) return false;})//data arrive as a string but we can parse it correctlyfunction processJson(data, statusText, xhr, $form){ my_data_parsed = JSON.parse(data);   }!#ruby def create....   render :js =>  { :status => false,:messages => @myobject.errors.full_messages}.to_json end 


Can you examine the post to the server with firebug, and paste the request headers here. We're looking to see that the Accept header is set to json. Also, what version of rails are you using?