zsljulius
zsljulius

Reputation: 4103

Rails form_tag remote json

I have my form set up like this

= form_tag stocks_path, method: 'get', remote: true, class: "form-horizontal" do
      %legend Define Your Universe
      .control-group
        = label_tag :min_cap, "Min Cap", class: "control-label"
        .controls
          = text_field_tag :min_cap, params[:min_cap], size: 5, maxlength: 6, class: "input-small"
      .control-group
        = label_tag :max_cap, "Max Cap", class: "control-label"
        .controls
          = text_field_tag :max_cap, params[:max_cap], size: 5, maxlength: 6, class: "input-small"
      .control-group
        = label_tag :size, "Size", class: "control-label"
        .controls
          = text_field_tag :size, params[:size], size: 5, maxlength: 2, class: "input-small"
      .form-actions
        = submit_tag "Submit", class: "btn btn-primary"

Then I have in my controller:

respond_to do |format|
      format.html
      format.js { render :json => {:stocks=>@stocks, :stats => @stats}
      # By default, json method does not know about extra none activerecord attributes!
    end

@stats is an array of numbers. Finally in my javascript, I have

  $("form").bind 'ajax:success', (xhr, data, status) -> 
    stocks = $.parseJSON(data.stocks)

Then issue here is that data.stocks does not get the stocks objects as json. In my console, I put a breakpoint at the line stocks = $.parseJSON(data.stocks). However, the callback function never get called, so I don't really see what's going on. But I see from the network tab (in chrome) that the form indeed got submitted and returned the desired javascript object. I am wondering why the callback function for success doesn't really get called.

Thanks for your help.

Upvotes: 0

Views: 1937

Answers (2)

zsljulius
zsljulius

Reputation: 4103

Ok, After all the efforts. I figure out the solution. It is weird, and I still couldn't find a good explanation for it. I changed my render line to format.js {render :json => {:stocks=>@stocks, :stats => @stats}, :content_type => 'application/json'}. I tried format.json, but the response header just keeps returning text/html instead of javscript. but format.js works with the additional option :content_type =>'application/json'. Any explanation will be greatly appreciated. Thanks

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160171

Use format.json { etc... } instead; check the difference in the response headers.

Upvotes: 0

Related Questions