1

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,

1
  • How are you sending the Post request? are you perhaps doing it via jQuery's $.post? Commented Nov 28, 2013 at 18:47

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

Although my logic tells me it should work, it do not. I am not sure why.
This is the standard way to build JS objects. Really weird if it doesn't work.
This is not correct because you'll receive {"attachment"=>"{\"id\":\"80\"}", "format"=>:json, "action"=>"the_action", "controller"=>"main_controller"} as the params in the rails server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.