Tarlen
Tarlen

Reputation: 3797

adding extra data to ajax response

I have this piece of code:

var jqxhr = $.ajax({
    url:      "/customers/shipments/get_carrier_products_and_prices_for_shipment.json",
    type:     "POST",
    dataType: "json",
    data:     data
})

and the last lines of controller:

if @carrier_products_and_prices.length > 0
    @digest = params[:digest]
    @html     = render_to_string(partial: "components/customers/shipments/carrier_products_and_prices_for_shipment_table.html.haml", locals: {carrier_products_and_prices: @carrier_products_and_prices})
else
    @html = render_to_string(partial: "components/customers/shipments/no_carrier_products_available.html.haml", locals: {carrier_products_and_prices: @carrier_products_and_prices})
end

Which hits a rails controller. My question is, how can I control/append extra data to the response object that rails returns? Right now, it only returns a html string, and I would like to also be able to send a response ID with it

Upvotes: 0

Views: 84

Answers (2)

Arvoreniad
Arvoreniad

Reputation: 510

It looks like your client is expecting a JSON body. Just create a hash of the values you want returned to the client and call render json: hash where hash contains the values you want to return to the client as JSON.

Upvotes: 2

Amadan
Amadan

Reputation: 198436

Since you're already using the JSON dataType, there's nothing stopping you from packing up your stuff in an object:

{
  "html": "<div>...</div>",
  "responseID": 69
}

Upvotes: 1

Related Questions