bymannan
bymannan

Reputation: 1383

Rails: How to turn JS object to array params

I have this JS object:

obj = {id: 80, attr_name: "avatar", style: "small", upload_path: null}

I then post this object as params with AJAX to the controller. What I would like to see in the params is something like this:

params[:attachment][:id] = 80
params[:attachment][:attr_name] = "avatar"

and so on and on...

So on the JS side I created an object that holds attachment params:

{attachment:obj}

While I do get params[:attachment] the result it [object Object].

How can I turn my JS object into an array inside params[:attachment]?

Thanks,

Upvotes: 1

Views: 1017

Answers (2)

jlstr
jlstr

Reputation: 3056

Assuming you're using jQuery (which is Rails default), this would work:

<h1>TEST</h1>

<script type="text/javascript">

  $(function() {

    params = {};
    params.attachment = {};
    params.attachment.id = 80;

    $.post( "/the_action", params, function(data) {
      alert("response");  
    }, "json");

  });

</script>

You may verify this in the controller like this:

class MainController < ApplicationController
  respond_to :html, :json
  def index

  end


  def the_action
    print params
    puts params[:attachment][:id]
    render nothing: true
  end

end

That should print the data in the format you desire.

Upvotes: 2

davidfurber
davidfurber

Reputation: 5520

One way is, instead of {attachment: obj} to make it like so:

postData = {
  "attachment[id]": obj.id,
  "attachment[attr_name]": obj.attr_name
}

Another method is to use stringify the JS object as JSON, and JSON.parse it on the other side.

However jQuery.ajax, when you pass an object to the "data" parameter, ought to send it along just fine as is. See: Post an object as data using Jquery Ajax

Upvotes: 3

Related Questions